This is a migrated thread and some comments may be shown as answers.

TypeCast error when persisting

5 Answers 146 Views
PersistenceFramework
This is a migrated thread and some comments may be shown as answers.
Oliver
Top achievements
Rank 1
Oliver asked on 21 Mar 2012, 03:37 PM

Hi,

I'm using Telerik V2011.3.1220.35 and when I try to persist dialog I have some problems.

Here is the errors I have in my log:
-----------------------------------------
1. Error occured during 'Load' file. Message: DisplayIndex out of range! Date
Nom du paramètre : displayIndex

2. Error occured during 'Save' file. Message: Impossible d'effectuer un cast d'un objet de type 'Telerik.Windows.Data.SortDescriptor' en type 'Telerik.Windows.Controls.GridView.ColumnSortDescriptor'.

3. When I run my application in my Visual Studion environment, I can see a lot of :

 

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll

 

that occured when I try to load from my PersistenceStorage class and the file to load does not exist. Do we have something we can do before loading a persisted file to see if the file exist?

Here is my class:
---------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Data;
using Telerik.Windows.Documents.FormatProviders.Txt;
using Telerik.Windows.Persistence;
using Telerik.Windows.Persistence.Services;
using Telerik.Windows.Persistence.Storage;
using Telerik.Windows.Zip;

using com.christiegrp.Neuron.Client;
using com.ChristieGrp.Infrastructure;

namespace com.christiegrp.Neuron.ClientApplication
{
    static public class PersistenceStorage
    {       
        #region Public methods.
        /// <summary>
        /// Load/Save all controls that contain "telerik:PersistenceManager.StorageId="..."
        /// The file location is "$APPDATA\IsolatedStorage\..."
        /// </summary>
        /// <param name="pPersistenceAction">Load/Save</param>
        /// <param name="pErrorMessage">Error received during the persistence.</param>
        /// <returns>true if successfull otherwise false</returns>
        static public bool Persist(PersistenceAction pPersistenceAction, out string pErrorMessage)
        {           
            pErrorMessage = string.Empty;
            PersistenceManager manager = new PersistenceManager();
            manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
            IsolatedStorageProvider storage = new IsolatedStorageProvider(manager);

            try
            {
                try
                {
                    if (pPersistenceAction == PersistenceAction.Load)
                    {
                        storage.LoadFromStorage(); // TO CHECK
                    }
                    else if (pPersistenceAction == PersistenceAction.Save)
                    {
                        storage.SaveToStorage(); // TO CHECK
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                    tracingTool.Log(GclLogger.Level.Error, "PERST001", "Error occured during '{0}' file. Message: {1}", pPersistenceAction.ToString(), ex.Message.ToString());
                    pErrorMessage = ex.Message;
                    return false;
                }
            }
            finally
            {
                manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
            }
        }

        /// <summary>
        /// Load/Save from/to stream object.
        /// </summary>
        /// <param name="pDataSource">If different from null, we persist load/save from/in database.</param>
        /// <param name="pObject">Object to load/save.</param>
        /// <param name="pStream">Stream that contain the serialized object. Object content is ignored if pDatabaseStorage is true.</param>
        /// <param name="pPersistenceAction">Load/Save</param>       
        /// <param name="pErrorMessage">Error received during the persistence.</param>
        /// <returns></returns>
        static public bool Persist(NeuronDataSource pDataSource, object pObject, ref Stream pStream, PersistenceAction pPersistenceAction, out string pErrorMessage)
        {
            // TODO: Compress/Uncompress the stream before save/load to/from database.

            mResult = true;
            pErrorMessage = string.Empty;
            PersistenceManager manager = new PersistenceManager();
            manager.PersistenceError += new Telerik.Windows.Persistence.Events.PersistenceErrorEventHandler(manager_PersistenceError);
            manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);

            try
            {
                if (pPersistenceAction == PersistenceAction.Load)
                {
                    if (pObject != null && pStream != null)
                    {
                        pStream.Position = 0L; // TO CHECK
                        manager.Load(pObject, pStream); // TO CHECK
                    }
                    else
                    {
                        pErrorMessage = "pObject and/or pStream cannot be null.";
                        GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                        tracingTool.Log(GclLogger.Level.Error, "PERST005", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), pErrorMessage);
                        mResult = false;
                    }
                }
                else if (pPersistenceAction == PersistenceAction.Save)
                {
                    if (pObject != null)
                    {
                        pStream = manager.Save(pObject); // TO CHECK
                    }
                    else
                    {
                        pErrorMessage = "pObject cannot be null.";
                        GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                        tracingTool.Log(GclLogger.Level.Error, "PERST006", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), pErrorMessage);
                        mResult = false;
                    }
                }
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST002", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), ex.Message.ToString());
                pErrorMessage = ex.Message;
                mResult = false;
            }
            finally
            {
                manager.PersistenceError -= new Telerik.Windows.Persistence.Events.PersistenceErrorEventHandler(manager_PersistenceError);
                manager.PropertyPersisting -= new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
                pErrorMessage = mErrorMessage;
            }

            return mResult;
        }

        /// <summary>
        /// Deleting all persistence files.
        /// </summary>
        /// <param name="pErrorMessage">Error receiving during deleting files.</param>
        static public void DeleteAll(out string pErrorMessage)
        {
            pErrorMessage = string.Empty;
            IsolatedStorageProvider iso = new IsolatedStorageProvider();
            try
            {
                iso.DeleteIsolatedStorageFiles();
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST007", "Error occured during deleting files. Message: {0}", ex.Message.ToString());
                pErrorMessage = ex.Message;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        private static void copyTo(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768]; // Fairly arbitrary size
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        /// <summary>
        /// Uncompress a stream.
        /// </summary>
        /// <param name="pStreamIn"></param>
        /// <param name="pStreamOut"></param>
        /// <returns></returns>
        private static bool uncompressStream(MemoryStream pStreamIn, out Stream pStreamOut)
        {
            pStreamOut = null;
            try
            {   
                //TODO: Uncompress stream
                return true;
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST003", "{0}", ex.Message.ToString());
                mErrorMessage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// Compream a stream.
        /// </summary>
        /// <param name="pStreamIn"></param>
        /// <param name="pStreamOut"></param>
        /// <returns></returns>
        private static bool compressStream(ref Stream pStreamIn, out MemoryStream pStreamOut)
        {
            pStreamOut = null;
            try
            {
                pStreamOut = new MemoryStream();
                ZipPackage package = ZipPackage.Create(pStreamOut);
                package.AddStream(pStreamIn, "WindowPersistedData");
                pStreamIn.Position = 0L;
                return true;
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST004", "{0}", ex.Message.ToString());
                mErrorMessage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// Event triggered when the stream persistence didn't worked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void manager_PersistenceError(object sender, Telerik.Windows.Persistence.Events.PersistenceErrorEventArgs e)
        {
            mErrorMessage = e.Exception.Message;
            mResult = false;
            throw new NotImplementedException();
        }

        /// <summary>
        /// This event is used to prevent any BroderBrush to have a transparent color when we persist an object.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void manager_PropertyPersisting(object sender, Telerik.Windows.Persistence.Events.PersistingPropertyEventArgs e)
        {
            //Not needed since version 2011.3.1116.35 of Telerik
            //if (e.Name == "BorderBrush")
            //    e.Cancel = true;
        }
        #endregion

        #region Private declarations.
        /// <summary>
        /// Persist a streaming object into or from database.
        /// </summary>
        /// <param name="pAction"></param>
        /// <param name="pStream"></param>
        /// <returns></returns>
        static private Boolean databaseStorage(PersistenceAction pAction, ref MemoryStream pStream)
        {
            Boolean result = true;

            if (pAction == PersistenceAction.Load)
            {
                throw new NotImplementedException();
            }
            else if (pAction == PersistenceAction.Save)
            {
                throw new NotImplementedException();
            }
           
            return result;
        }
        #endregion

        #region Enumerators.
        public enum PersistenceAction { Load, Save }
        #endregion

        #region Private declarations.
        static private string mErrorMessage;
        static private bool mResult;
        #endregion
    }

    //====================================================================================
    //
    //====================================================================================
    public class DockingCustomPropertyProvider : ICustomPropertyProvider
    {
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create two custom properties to serialize the Layout of the RadDocking and the Content of the RadPanes
            return new CustomPropertyInfo[]
        {
            new CustomPropertyInfo("Layout", typeof(string)),
            new CustomPropertyInfo("Content", typeof(List<PaneProxy>)) { AllowCreateInstance =false, TreatAsUI = false},
        };
        }

        public void InitializeObject(object context)
        {
        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            if (customPropertyInfo.Name == "Content")
            {
                // See remarks in ProvideValue method:
                // provide the values on which the saved properties will be restored upon
                RadDocking docking = context as RadDocking;
                List<PaneProxy> proxies = new List<PaneProxy>();
                foreach (RadPane pane in this.GetOrderedPanes(docking).ToArray())
                {
                    proxies.Add(new PaneProxy() { Content = pane.Content });
                }
                return proxies;
            }
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadDocking docking = context as RadDocking;
            if (customPropertyInfo.Name == "Layout")
            {
                // let the RadDocking save the layout of the Panes:
                return this.SaveLayoutAsString(docking);
            }
            else if (customPropertyInfo.Name == "Content")
            {
                // create proxies for all of the Panes and save their content
                IEnumerable<RadPane> panes = this.GetOrderedPanes(docking);
                List<PaneProxy> proxies = new List<PaneProxy>();
                foreach (RadPane pane in panes)
                {
                    proxies.Add(new PaneProxy() { Content = pane.Content });
                }
                return proxies;
            }
            return null;
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            if (customPropertyInfo.Name == "Layout")
            {
                // let the RadDocking load the layout of the RadPanes
                this.LoadLayoutFromString(value.ToString(), context as RadDocking);
            }
            else if (customPropertyInfo.Name == "Content")
            {
                // the PersistenceManager does not re-create UI elements - in this case the Content of the RadPane.
                // So, instead of providing a value on which the saved properties will be applied,
                // we will use the InitializeValue method.
            }
        }

        private string SaveLayoutAsString(RadDocking instance)
        {
            MemoryStream stream = new MemoryStream();
            instance.SaveLayout(stream);

            stream.Seek(0, SeekOrigin.Begin);

            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }

        private void LoadLayoutFromString(string xml, RadDocking instance)
        {
            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                stream.Seek(0, SeekOrigin.Begin);
                instance.LoadLayout(stream);
            }
        }

        private IEnumerable<RadPane> GetOrderedPanes(RadDocking docking)
        {
            // get the RadPanes always in the same order:
            RadPane[] array = docking.Panes.ToArray();
            Array.Sort(array, new RadPaneComparer());
            return array;
        }
    }

    public class RadPaneComparer : IComparer<RadPane>
    {
        int IComparer<RadPane>.Compare(RadPane x, RadPane y)
        {
            // compare RadPanes by their serialization tag:
            string xSerializationTag = RadDocking.GetSerializationTag(x);
            string ySerializationTag = RadDocking.GetSerializationTag(y);

            return xSerializationTag.CompareTo(ySerializationTag);
        }
    }

    //====================================================================================
    //
    //====================================================================================
    public class GridViewCustomPropertyProvider : ICustomPropertyProvider
    {
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create three custom properties to persist the Columns, Sorting and Group descriptors using proxy objects
            return new CustomPropertyInfo[]
                {
                    new CustomPropertyInfo("Columns", typeof(List<ColumnProxy>)),
                    new CustomPropertyInfo("SortDescriptors", typeof(List<SortDescriptorProxy>)),
                    new CustomPropertyInfo("FilterDescriptors", typeof(List<FilterSetting>)),
                    new CustomPropertyInfo("GroupDescriptors", typeof(List<GroupDescriptorProxy>)),
                };
        }

        public void InitializeObject(object context)
        {
            if (context is RadGridView)
            {
                RadGridView gridView = context as RadGridView;
                gridView.SortDescriptors.Clear();
                gridView.GroupDescriptors.Clear();
                gridView.FilterDescriptors.Clear();
            }
        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadGridView gridView = context as RadGridView;
            if (customPropertyInfo.Name == "Columns")
            {
                // create proxies for all of the columns and save only specific properties
                List<ColumnProxy> proxies = new List<ColumnProxy>();
                foreach (GridViewColumn column in gridView.Columns)
                {
                    proxies.Add(new ColumnProxy()
                    {
                        UniqueName = column.UniqueName,
                        Header = column.Header.ToString(),
                        DisplayOrder = column.DisplayIndex,
                        Width = column.Width,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "SortDescriptors")
            {
                // create proxies for all of the sort descriptors and save only specific properties
                List<SortDescriptorProxy> proxies = new List<SortDescriptorProxy>();
                foreach (ColumnSortDescriptor descriptor in gridView.SortDescriptors)
                {
                    proxies.Add(new SortDescriptorProxy()
                    {
                        ColumnUniqueName = descriptor.Column.UniqueName,
                        SortDirection = descriptor.SortDirection,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "GroupDescriptors")
            {
                // create proxies for all of the group descriptors and save only specific properties
                List<GroupDescriptorProxy> proxies = new List<GroupDescriptorProxy>();
                foreach (ColumnGroupDescriptor descriptor in gridView.GroupDescriptors)
                {
                    proxies.Add(new GroupDescriptorProxy()
                    {
                        ColumnUniqueName = descriptor.Column.UniqueName,
                        SortDirection = descriptor.SortDirection,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "FilterDescriptors")
            {
                // create proxies for all of the filter descriptors and save only specific properties
                List<FilterSetting> proxies = new List<FilterSetting>();               
                foreach (IColumnFilterDescriptor cfd in gridView.FilterDescriptors.OfType<IColumnFilterDescriptor>())
                {
                    FilterSetting setting = new FilterSetting();

                    if (cfd.FieldFilter.Filter1.Value != Telerik.Windows.Data.FilterDescriptor.UnsetValue)
                    {
                        setting.Filter1 = new FilterDescriptorProxy();
                        setting.Filter1.Member = cfd.FieldFilter.Filter1.Member;
                        setting.Filter1.Operator = cfd.FieldFilter.Filter1.Operator;
                        setting.Filter1.Value = cfd.FieldFilter.Filter1.Value;
                    }

                    if (cfd.FieldFilter.Filter2.Value != Telerik.Windows.Data.FilterDescriptor.UnsetValue)
                    {
                        setting.Filter2 = new FilterDescriptorProxy();
                        setting.Filter2.Member = cfd.FieldFilter.Filter2.Member;
                        setting.Filter2.Operator = cfd.FieldFilter.Filter2.Operator;
                        setting.Filter2.Value = cfd.FieldFilter.Filter2.Value;
                    }
                    foreach (Telerik.Windows.Data.FilterDescriptor fd in cfd.DistinctFilter.FilterDescriptors.OfType<Telerik.Windows.Data.FilterDescriptor>())
                    {
                        if (fd.Value == Telerik.Windows.Data.FilterDescriptor.UnsetValue)
                        {
                            continue;
                        }

                        FilterDescriptorProxy fds = new FilterDescriptorProxy();
                        fds.Member = fd.Member;
                        fds.Operator = fd.Operator;
                        fds.Value = fd.Value;
                        setting.SelectedDistinctValues.Add(fds);
                    }

                    proxies.Add(setting);
                    setting.PropertyName = setting.PropertyName = cfd.Column.DataMemberBinding.Path.Path;
                }
                return proxies;
            }
            return null;
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            RadGridView gridView = context as RadGridView;
            if (customPropertyInfo.Name == "Columns")
            {
                List<ColumnProxy> savedProxies = value as List<ColumnProxy>;

                // restore properties on the saved columns:
                foreach (ColumnProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.UniqueName);
                    if (column != null)
                    {
                        column.DisplayIndex = proxy.DisplayOrder;
                        column.Header = proxy.Header;
                        column.Width = proxy.Width;
                    }
                }
            }
            else if (customPropertyInfo.Name == "SortDescriptors")
            {
                gridView.SortDescriptors.Clear();
                List<SortDescriptorProxy> savedProxies = value as List<SortDescriptorProxy>;

                // restore properties on the saved sort descriptors:
                foreach (SortDescriptorProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.ColumnUniqueName);                   
                    gridView.SortDescriptors.Add(new ColumnSortDescriptor() { Column = column, SortDirection = proxy.SortDirection });
                }
            }
            else if (customPropertyInfo.Name == "GroupDescriptors")
            {
                gridView.GroupDescriptors.Clear();
                List<GroupDescriptorProxy> savedProxies = value as List<GroupDescriptorProxy>;

                // restore properties on the saved group descriptors:
                foreach (GroupDescriptorProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.ColumnUniqueName);
                    gridView.GroupDescriptors.Add(new ColumnGroupDescriptor() { Column = column, SortDirection = proxy.SortDirection });
                }
            }
            else if (customPropertyInfo.Name == "FilterDescriptors")
            {
                gridView.FilterDescriptors.Clear();
                List<FilterSetting> settings = value as List<FilterSetting>;
                foreach (FilterSetting setting in settings)
                {
                    FilterSetting currentSetting = setting;

                    GridViewDataColumn matchingColumn =
                    (from column in gridView.Columns.OfType<GridViewDataColumn>()
                     where column.DataMemberBinding.Path.Path == currentSetting.PropertyName
                     select column).FirstOrDefault();

                    if (matchingColumn != null)
                    {
                        ColumnFilterDescriptor cfd = new ColumnFilterDescriptor(matchingColumn);

                        if (setting.Filter1 != null && setting.Filter1.Member != null)
                        {
                            cfd.FieldFilter.Filter1.Member = setting.Filter1.Member;
                            cfd.FieldFilter.Filter1.Operator = setting.Filter1.Operator;
                            cfd.FieldFilter.Filter1.Value = setting.Filter1.Value;
                        }

                        if (setting.Filter2 != null && setting.Filter2.Member != null)
                        {
                            cfd.FieldFilter.Filter2.Member = setting.Filter2.Member;
                            cfd.FieldFilter.Filter2.Operator = setting.Filter2.Operator;
                            cfd.FieldFilter.Filter2.Value = setting.Filter2.Value;
                        }

                        foreach (FilterDescriptorProxy fds in setting.SelectedDistinctValues)
                        {
                            Telerik.Windows.Data.FilterDescriptor fd = new Telerik.Windows.Data.FilterDescriptor();
                            fd.Member = fds.Member;
                            fd.Operator = fds.Operator;
                            fd.Value = fds.Value;
                            cfd.DistinctFilter.FilterDescriptors.Add(fd);
                        }
                        setting.PropertyName = cfd.Column.DataMemberBinding.Path.Path;

                        gridView.FilterDescriptors.Add(cfd);
                    }
                }
            }
        }

        private GridViewColumn GetColumnInstance(RadGridView gridView, string uniqueName)
        {
            foreach (GridViewColumn column in gridView.Columns)
            {
                if (column.UniqueName == uniqueName)
                    return column;
            }
            return null;
        }
    }

    public class ColumnProxy
    {
        public string UniqueName { get; set; }
        public int DisplayOrder { get; set; }
        public string Header { get; set; }
        public GridViewLength Width { get; set; }
    }

    public class SortDescriptorProxy
    {
        public string ColumnUniqueName { get; set; }
        public ListSortDirection SortDirection { get; set; }
    }

    public class GroupDescriptorProxy
    {
        public string ColumnUniqueName { get; set; }
        public ListSortDirection? SortDirection { get; set; }
    }

    public class FilterDescriptorProxy
    {
        public string Member { get; set; }
        public FilterOperator Operator { get; set; }
        public object Value { get; set; }
        public bool IsCaseSEnsitive { get; set; }
    }

    public class FilterSetting
    {
        public string PropertyName { get; set; }
        List<FilterDescriptorProxy> _SelectedDistinctValues;
        public List<FilterDescriptorProxy> SelectedDistinctValues
        {
            get
            {
                if (_SelectedDistinctValues == null)
                {
                    _SelectedDistinctValues = new List<FilterDescriptorProxy>();
                }
                return _SelectedDistinctValues;
            }
        }

        FilterDescriptorProxy _Filter1;
        public FilterDescriptorProxy Filter1
        {
            get
            {
                return _Filter1;
            }
            set
            {
                _Filter1 = value;
            }
        }

        FilterDescriptorProxy _Filter2;
        public FilterDescriptorProxy Filter2
        {
            get
            {
                return _Filter2;
            }
            set
            {
                _Filter2 = value;
            }
        }
    }

    //====================================================================================
    //
    //====================================================================================
    public class RichTextBoxCustomPropertyProvider : ICustomPropertyProvider
    {
        #region ICustomPropertyProvider Members
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create two custom properties to serialize the RichTextBox properties and content
            return new CustomPropertyInfo[]
                {
                    new CustomPropertyInfo("Content", typeof(string)),
                    new CustomPropertyInfo("AcceptsReturn", typeof(bool)),
                };
        }

        public void InitializeObject(object context)
        {

        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadRichTextBox owner = context as RadRichTextBox;
            if (customPropertyInfo.Name == "Content")
            {
                TxtFormatProvider provider = new TxtFormatProvider();
                string content = provider.Export(owner.Document);
                return content;
            }
            else
            {
                return this.GetValueSafely(customPropertyInfo.Name, owner);
            }
        }

        private object GetValueSafely(string propertyName, RadRichTextBox owner)
        {
            PropertyInfo info = owner.GetType().GetProperty(propertyName);
            if (info != null)
            {
                return info.GetValue(owner, null);
            }
            else
                throw new Exception();
        }

        private void SetValueSafely(string propertyName, object value, RadRichTextBox owner)
        {
            PropertyInfo info = owner.GetType().GetProperty(propertyName);
            if (info != null)
            {
                info.SetValue(owner, value, null);
            }
            else
                throw new Exception();
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            RadRichTextBox owner = context as RadRichTextBox;
            if (customPropertyInfo.Name == "Content")
            {
                TxtFormatProvider provider = new TxtFormatProvider();
                owner.Document = provider.Import(value.ToString());
            }
            else
            {
                this.SetValueSafely(customPropertyInfo.Name, value, owner);
            }
        }

        #endregion
    }

    //====================================================================================
    //
    //====================================================================================
    public class PaneProxy
    {
        public object Content { get; set; }
    }
}

5 Answers, 1 is accepted

Sort by
0
Alex Fidanov
Telerik team
answered on 26 Mar 2012, 08:27 AM
Hello,

The exceptions are probably occuring because of the breaking changes in the GridView control as of this release. I see, that you are still using the old custom property provider for the GridView. I would recommend updating it with the new one, which you can find here. Regarding issue 1: this is probably caused by saving the column's index of -1. Please note that this is not supported, and you can modify the custom property provider so that -1 would not be saved as column's display index.

 Please let me know if that resolves all the issues?

Regards,
Alex Fidanov
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Oliver
Top achievements
Rank 1
answered on 26 Mar 2012, 04:54 PM

Hi Alex,

 

I tried to ugraded my code  using your "you can find here" link ad I realize the it's a demo for Silverlight and I got a lot of problem. One of them is : Error 1 'Telerik.Windows.Controls.GridViewDataColumn' does not contain a definition for 'ColumnFilterDescriptor' and no extension method 'ColumnFilterDescriptor' accepting a first argument of type 'Telerik.Windows.Controls.GridViewDataColumn' could be found (are you missing a using directive or an assembly reference?) D:\Developpement\GestX.Courant\RisGC\Client\ClientHelper\PersistenceStorage.cs 522 45 ClientHelper

I didn't go further.

Thank's

0
Alex Fidanov
Telerik team
answered on 29 Mar 2012, 08:40 AM
Hello,

I apologize for the inconvenience. I am attaching the correct custom property descriptor. You can also find these files in the local WPF QSF for Q1 2012.

Greetings,
Alex Fidanov
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
0
Oliver
Top achievements
Rank 1
answered on 29 Mar 2012, 03:05 PM
Hi,

no problem :)

With your code, I have the following error (As I said in my main post, I use Telerik V2011.3.1220.35):

Error 2 'Telerik.Windows.Controls.GridViewDataColumn' ne contient pas une définition pour 'ColumnFilterDescriptor' et aucune méthode d'extension 'ColumnFilterDescriptor' acceptant un premier argument de type 'Telerik.Windows.Controls.GridViewDataColumn' n'a été trouvée (une directive using ou une référence d'assembly est-elle manquante ?) D:\Developpement\GestX.Courant\RisGC\Client\ClientHelper\PersistenceStorage.cs 549 45 ClientHelper

Hre is my class:

//====================================================================================
// Author.......: Alain Gosselin
// Creation date: 2011-10-12
// Fonction.....: Permit to serialize an object and save or restore his state.
//====================================================================================
// Date       Prg  TT#    Details
// ---------- ---- ------ ------------------------------------------------------------
//
//====================================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Data;
using Telerik.Windows.Documents.FormatProviders.Txt;
using Telerik.Windows.Persistence;
using Telerik.Windows.Persistence.Services;
using Telerik.Windows.Persistence.Storage;
using Telerik.Windows.Zip;

using com.christiegrp.Neuron.Client;
using com.ChristieGrp.Infrastructure;

namespace com.christiegrp.Neuron.ClientApplication
{
    static public class PersistenceStorage
    {       
        #region Public methods.
        /// <summary>
        /// Set a StorageId before Loading/Saving a control and removing it's StorageId after the action was taken.
        /// The file location is "$APPDATA\IsolatedStorage\..."
        /// </summary>
        /// <param name="pPersistenceAction">Load/Save</param>
        /// <param name="pObjectToPersist">Object to persist.</param>
        /// <param name="pStorageId">StorageId of the object to persist. Null mean that a custom StorageId will be use.</param>
        /// <param name="pErrorMessage">Error received during the persistence.</param>
        /// <returns>true if successfull otherwise false</returns>
        static public bool Persist(PersistenceAction pPersistenceAction, System.Windows.DependencyObject pObjectToPersist, string pStorageId, out string pErrorMessage)
        {           
            bool result = false;
            pErrorMessage = string.Empty;

            if (pObjectToPersist != null)
            {
                // Validate if we need to generate a custom StorageId.
                if (string.IsNullOrEmpty(pStorageId))
                {
                    pStorageId = GetCustomStorageId(pObjectToPersist);
                }

                try
                {
                    PersistenceManager.SetStorageId(pObjectToPersist, pStorageId);
                    result = Persist(pPersistenceAction, out pErrorMessage);
                }
                finally
                {
                    pObjectToPersist.ClearValue(PersistenceManager.StorageIdProperty);
                }
            }

            return result;
        }

        /// <summary>
        /// Load/Save all controls that contain "telerik:PersistenceManager.StorageId="..."
        /// The file location is "$APPDATA\IsolatedStorage\..."
        /// </summary>
        /// <param name="pPersistenceAction">Load/Save</param>
        /// <param name="pErrorMessage">Error received during the persistence.</param>
        /// <returns>true if successfull otherwise false</returns>
        static public bool Persist(PersistenceAction pPersistenceAction, out string pErrorMessage)
        {           
            pErrorMessage = string.Empty;
            PersistenceManager manager = new PersistenceManager();
            manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
            IsolatedStorageProvider storage = new IsolatedStorageProvider(manager);

            try
            {
                try
                {
                    if (pPersistenceAction == PersistenceAction.Load)
                    {
                        //storage.LoadFromStorage(); // TODO CHECK
                    }
                    else if (pPersistenceAction == PersistenceAction.Save)
                    {
                        //storage.SaveToStorage(); // TODO CHECK
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                    tracingTool.Log(GclLogger.Level.Error, "PERST001", "Error occured during '{0}' file. Message: {1}", pPersistenceAction.ToString(), ex.ToString());
                    pErrorMessage = ex.Message;
                    return false;
                }
            }
            finally
            {
                manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
            }
        }

        /// <summary>
        /// Load/Save from/to stream object.
        /// </summary>
        /// <param name="pDataSource">If different from null, we persist load/save from/in database.</param>
        /// <param name="pObject">Object to load/save.</param>
        /// <param name="pStream">Stream that contain the serialized object. Object content is ignored if pDatabaseStorage is true.</param>
        /// <param name="pPersistenceAction">Load/Save</param>       
        /// <param name="pErrorMessage">Error received during the persistence.</param>
        /// <returns></returns>
        static public bool Persist(NeuronDataSource pDataSource, object pObject, ref Stream pStream, PersistenceAction pPersistenceAction, out string pErrorMessage)
        {
            // TODO: Compress/Uncompress the stream before save/load to/from database.

            mResult = true;
            pErrorMessage = string.Empty;
            PersistenceManager manager = new PersistenceManager();
            manager.PersistenceError += new Telerik.Windows.Persistence.Events.PersistenceErrorEventHandler(manager_PersistenceError);
            manager.PropertyPersisting += new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);

            try
            {
                if (pPersistenceAction == PersistenceAction.Load)
                {
                    if (pObject != null && pStream != null)
                    {
                        pStream.Position = 0L; // TO CHECK
                        manager.Load(pObject, pStream); // TO CHECK
                    }
                    else
                    {
                        pErrorMessage = "pObject and/or pStream cannot be null.";
                        GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                        tracingTool.Log(GclLogger.Level.Error, "PERST005", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), pErrorMessage);
                        mResult = false;
                    }
                }
                else if (pPersistenceAction == PersistenceAction.Save)
                {
                    if (pObject != null)
                    {
                        pStream = manager.Save(pObject); // TO CHECK
                    }
                    else
                    {
                        pErrorMessage = "pObject cannot be null.";
                        GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                        tracingTool.Log(GclLogger.Level.Error, "PERST006", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), pErrorMessage);
                        mResult = false;
                    }
                }
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST002", "Error occured during '{0}' stream. Message: {1}", pPersistenceAction.ToString(), ex.Message.ToString());
                pErrorMessage = ex.Message;
                mResult = false;
            }
            finally
            {
                manager.PersistenceError -= new Telerik.Windows.Persistence.Events.PersistenceErrorEventHandler(manager_PersistenceError);
                manager.PropertyPersisting -= new Telerik.Windows.Persistence.Events.PropertyPersistingEventHandler(manager_PropertyPersisting);
                pErrorMessage = mErrorMessage;
            }

            return mResult;
        }

        /// <summary>
        /// Deleting all persistence files.
        /// </summary>
        /// <param name="pErrorMessage">Error receiving during deleting files.</param>
        static public void DeleteAll(out string pErrorMessage)
        {
            pErrorMessage = string.Empty;
            IsolatedStorageProvider iso = new IsolatedStorageProvider();
            try
            {
                iso.DeleteIsolatedStorageFiles();
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST007", "Error occured during deleting files. Message: {0}", ex.Message.ToString());
                pErrorMessage = ex.Message;
            }
        }

        /// <summary>
        /// Generate a custom StorageId.
        /// </summary>
        /// <param name="pObjectToPersist"></param>
        /// <returns></returns>
        static public string GetCustomStorageId(System.Windows.DependencyObject pObjectToPersist)
        {
            string customStorageId = string.Empty;
           

            if (pObjectToPersist != null)
            {
                Assembly assembly = pObjectToPersist.GetType().Assembly;
                customStorageId = assembly.GetName().Name + "." + pObjectToPersist.GetType().Name;               
            }

            return customStorageId;
        }
        #endregion

        #region Private methods.
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        private static void copyTo(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768]; // Fairly arbitrary size
            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }

        /// <summary>
        /// Uncompress a stream.
        /// </summary>
        /// <param name="pStreamIn"></param>
        /// <param name="pStreamOut"></param>
        /// <returns></returns>
        private static bool uncompressStream(MemoryStream pStreamIn, out Stream pStreamOut)
        {
            pStreamOut = null;
            try
            {   
                //TODO: Uncompress stream
                return true;
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST003", "{0}", ex.Message.ToString());
                mErrorMessage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// Compream a stream.
        /// </summary>
        /// <param name="pStreamIn"></param>
        /// <param name="pStreamOut"></param>
        /// <returns></returns>
        private static bool compressStream(ref Stream pStreamIn, out MemoryStream pStreamOut)
        {
            pStreamOut = null;
            try
            {
                pStreamOut = new MemoryStream();
                ZipPackage package = ZipPackage.Create(pStreamOut);
                package.AddStream(pStreamIn, "WindowPersistedData");
                pStreamIn.Position = 0L;
                return true;
            }
            catch (Exception ex)
            {
                GclLogger tracingTool = GclLogger.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                tracingTool.Log(GclLogger.Level.Error, "PERST004", "{0}", ex.Message.ToString());
                mErrorMessage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// Event triggered when the stream persistence didn't worked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void manager_PersistenceError(object sender, Telerik.Windows.Persistence.Events.PersistenceErrorEventArgs e)
        {
            mErrorMessage = e.Exception.Message;
            mResult = false;
            throw new NotImplementedException();
        }

        /// <summary>
        /// This event is used to prevent any BroderBrush to have a transparent color when we persist an object.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void manager_PropertyPersisting(object sender, Telerik.Windows.Persistence.Events.PersistingPropertyEventArgs e)
        {
            //Not needed since version 2011.3.1116.35 of Telerik
            //if (e.Name == "BorderBrush")
            //    e.Cancel = true;
        }
        #endregion

        #region Private declarations.
        /// <summary>
        /// Persist a streaming object into or from database.
        /// </summary>
        /// <param name="pAction"></param>
        /// <param name="pStream"></param>
        /// <returns></returns>
        static private Boolean databaseStorage(PersistenceAction pAction, ref MemoryStream pStream)
        {
            Boolean result = true;

            if (pAction == PersistenceAction.Load)
            {
                throw new NotImplementedException();
            }
            else if (pAction == PersistenceAction.Save)
            {
                throw new NotImplementedException();
            }
           
            return result;
        }
        #endregion

        #region Enumerators.
        public enum PersistenceAction { Load, Save }
        #endregion

        #region Private declarations.
        static private string mErrorMessage;
        static private bool mResult;
        #endregion
    }

    //====================================================================================
    //
    //====================================================================================
    public class DockingCustomPropertyProvider : ICustomPropertyProvider
    {
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create two custom properties to serialize the Layout of the RadDocking and the Content of the RadPanes
            return new CustomPropertyInfo[]
        {
            new CustomPropertyInfo("Layout", typeof(string)),
            new CustomPropertyInfo("Content", typeof(List<PaneProxy>)) { AllowCreateInstance =false, TreatAsUI = false},
        };
        }

        public void InitializeObject(object context)
        {
        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            if (customPropertyInfo.Name == "Content")
            {
                // See remarks in ProvideValue method:
                // provide the values on which the saved properties will be restored upon
                RadDocking docking = context as RadDocking;
                List<PaneProxy> proxies = new List<PaneProxy>();
                foreach (RadPane pane in this.GetOrderedPanes(docking).ToArray())
                {
                    proxies.Add(new PaneProxy() { Content = pane.Content });
                }
                return proxies;
            }
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadDocking docking = context as RadDocking;
            if (customPropertyInfo.Name == "Layout")
            {
                // let the RadDocking save the layout of the Panes:
                return this.SaveLayoutAsString(docking);
            }
            else if (customPropertyInfo.Name == "Content")
            {
                // create proxies for all of the Panes and save their content
                IEnumerable<RadPane> panes = this.GetOrderedPanes(docking);
                List<PaneProxy> proxies = new List<PaneProxy>();
                foreach (RadPane pane in panes)
                {
                    proxies.Add(new PaneProxy() { Content = pane.Content });
                }
                return proxies;
            }
            return null;
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            if (customPropertyInfo.Name == "Layout")
            {
                // let the RadDocking load the layout of the RadPanes
                this.LoadLayoutFromString(value.ToString(), context as RadDocking);
            }
            else if (customPropertyInfo.Name == "Content")
            {
                // the PersistenceManager does not re-create UI elements - in this case the Content of the RadPane.
                // So, instead of providing a value on which the saved properties will be applied,
                // we will use the InitializeValue method.
            }
        }

        private string SaveLayoutAsString(RadDocking instance)
        {
            MemoryStream stream = new MemoryStream();
            instance.SaveLayout(stream);

            stream.Seek(0, SeekOrigin.Begin);

            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }

        private void LoadLayoutFromString(string xml, RadDocking instance)
        {
            using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                stream.Seek(0, SeekOrigin.Begin);
                instance.LoadLayout(stream);
            }
        }

        private IEnumerable<RadPane> GetOrderedPanes(RadDocking docking)
        {
            // get the RadPanes always in the same order:
            RadPane[] array = docking.Panes.ToArray();
            Array.Sort(array, new RadPaneComparer());
            return array;
        }
    }

    public class RadPaneComparer : IComparer<RadPane>
    {
        int IComparer<RadPane>.Compare(RadPane x, RadPane y)
        {
            // compare RadPanes by their serialization tag:
            string xSerializationTag = RadDocking.GetSerializationTag(x);
            string ySerializationTag = RadDocking.GetSerializationTag(y);

            return xSerializationTag.CompareTo(ySerializationTag);
        }
    }

    //====================================================================================
    //
    //====================================================================================
    public class GridViewCustomPropertyProvider : ICustomPropertyProvider
    {
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create three custom properties to persist the Columns, Sorting and Group descriptors using proxy objects
            return new CustomPropertyInfo[]
            {
                new CustomPropertyInfo("Columns", typeof(List<ColumnProxy>)),
                new CustomPropertyInfo("SortDescriptors", typeof(List<SortDescriptorProxy>)),
                new CustomPropertyInfo("FilterDescriptors", typeof(List<FilterSetting>)),
                new CustomPropertyInfo("GroupDescriptors", typeof(List<GroupDescriptorProxy>)),
            };
        }

        public void InitializeObject(object context)
        {
            if (context is RadGridView)
            {
                RadGridView gridView = context as RadGridView;
                gridView.SortDescriptors.Clear();
                gridView.GroupDescriptors.Clear();
                gridView.FilterDescriptors.Clear();
            }
        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadGridView gridView = context as RadGridView;
            if (customPropertyInfo.Name == "Columns")
            {
                // create proxies for all of the columns and save only specific properties
                List<ColumnProxy> proxies = new List<ColumnProxy>();
                foreach (GridViewColumn column in gridView.Columns)
                {
                    proxies.Add(new ColumnProxy()
                    {
                        UniqueName = column.UniqueName,
                        Header = column.Header.ToString(),
                        DisplayOrder = column.DisplayIndex,
                        Width = column.Width,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "SortDescriptors")
            {
                // create proxies for all of the sort descriptors and save only specific properties
                List<SortDescriptorProxy> proxies = new List<SortDescriptorProxy>();
                foreach (ColumnSortDescriptor descriptor in gridView.SortDescriptors)
                {
                    proxies.Add(new SortDescriptorProxy()
                    {
                        ColumnUniqueName = descriptor.Column.UniqueName,
                        SortDirection = descriptor.SortDirection,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "GroupDescriptors")
            {
                // create proxies for all of the group descriptors and save only specific properties
                List<GroupDescriptorProxy> proxies = new List<GroupDescriptorProxy>();
                foreach (ColumnGroupDescriptor descriotor in gridView.GroupDescriptors)
                {
                    proxies.Add(new GroupDescriptorProxy()
                    {
                        ColumnUniqueName = descriotor.Column.UniqueName,
                        SortDirection = descriotor.SortDirection,
                    });
                }
                return proxies;
            }
            else if (customPropertyInfo.Name == "FilterDescriptors")
            {
                List<FilterSetting> settings = new List<FilterSetting>();

                foreach (GridViewDataColumn column in gridView.Columns
                    .OfType<GridViewDataColumn>()
                    .Where(column => column.ColumnFilterDescriptor.IsActive))
                {
                    FilterSetting setting = new FilterSetting();

                    setting.ColumnUniqueName = column.UniqueName;

                    if (column.ColumnFilterDescriptor.FieldFilter.Filter1.IsActive)
                    {
                        setting.Filter1 = new FilterDescriptorProxy();
                        setting.Filter1.Operator = column.ColumnFilterDescriptor.FieldFilter.Filter1.Operator;
                        setting.Filter1.Value = column.ColumnFilterDescriptor.FieldFilter.Filter1.Value;
                        setting.Filter1.IsCaseSensitive = column.ColumnFilterDescriptor.FieldFilter.Filter1.IsCaseSensitive;
                    }

                    if (column.ColumnFilterDescriptor.FieldFilter.Filter2.IsActive)
                    {
                        setting.Filter2 = new FilterDescriptorProxy();
                        setting.Filter2.Operator = column.ColumnFilterDescriptor.FieldFilter.Filter2.Operator;
                        setting.Filter2.Value = column.ColumnFilterDescriptor.FieldFilter.Filter2.Value;
                        setting.Filter2.IsCaseSensitive = column.ColumnFilterDescriptor.FieldFilter.Filter2.IsCaseSensitive;
                    }

                    foreach (object distinctValue in column.ColumnFilterDescriptor.DistinctFilter.DistinctValues)
                    {
                        setting.SelectedDistinctValues.Add(distinctValue);
                    }

                    settings.Add(setting);
                }

                return settings;
            }

            return null;
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            RadGridView gridView = context as RadGridView;
            if (customPropertyInfo.Name == "Columns")
            {
                List<ColumnProxy> savedProxies = value as List<ColumnProxy>;

                // restore properties on the saved columns:
                foreach (ColumnProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.UniqueName);
                    if (column != null)
                    {
                        column.DisplayIndex = proxy.DisplayOrder;
                        column.Header = proxy.Header;
                        column.Width = proxy.Width;
                    }
                }
            }
            else if (customPropertyInfo.Name == "SortDescriptors")
            {
                gridView.SortDescriptors.Clear();
                List<SortDescriptorProxy> savedProxies = value as List<SortDescriptorProxy>;

                // restore properties on the saved sort descriptors:
                foreach (SortDescriptorProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.ColumnUniqueName);
                    gridView.SortDescriptors.Add(new ColumnSortDescriptor() { Column = column, SortDirection = proxy.SortDirection });
                }
            }
            else if (customPropertyInfo.Name == "GroupDescriptors")
            {
                gridView.GroupDescriptors.Clear();
                List<GroupDescriptorProxy> savedProxies = value as List<GroupDescriptorProxy>;

                // restore properties on the saved group descriptors:
                foreach (GroupDescriptorProxy proxy in savedProxies)
                {
                    GridViewColumn column = this.GetColumnInstance(gridView, proxy.ColumnUniqueName);
                    gridView.GroupDescriptors.Add(new ColumnGroupDescriptor() { Column = column, SortDirection = proxy.SortDirection });
                }
            }
            else if (customPropertyInfo.Name == "FilterDescriptors")
            {
                gridView.FilterDescriptors.SuspendNotifications();

                foreach (var c in gridView.Columns)
                {
                    if (c.ColumnFilterDescriptor.IsActive)
                    {
                        c.ClearFilters();
                    }
                }

                List<FilterSetting> settings = value as List<FilterSetting>;

                foreach (FilterSetting setting in settings)
                {
                    GridViewDataColumn column = gridView.Columns
                        .OfType<GridViewDataColumn>()
                        .Single(c => c.UniqueName == setting.ColumnUniqueName);

                    if (column != null)
                    {
                        IColumnFilterDescriptor cfd = column.ColumnFilterDescriptor;

                        if (setting.Filter1 != null)
                        {
                            cfd.FieldFilter.Filter1.Operator = setting.Filter1.Operator;
                            cfd.FieldFilter.Filter1.Value = setting.Filter1.Value;
                            cfd.FieldFilter.Filter1.IsCaseSensitive = setting.Filter1.IsCaseSensitive;
                        }

                        if (setting.Filter2 != null)
                        {
                            cfd.FieldFilter.Filter2.Operator = setting.Filter2.Operator;
                            cfd.FieldFilter.Filter2.Value = setting.Filter2.Value;
                            cfd.FieldFilter.Filter2.IsCaseSensitive = setting.Filter2.IsCaseSensitive;
                        }

                        foreach (object distinctValue in setting.SelectedDistinctValues)
                        {
                            cfd.DistinctFilter.AddDistinctValue(distinctValue);
                        }
                    }
                }

                gridView.FilterDescriptors.ResumeNotifications();
            }
        }

        private GridViewColumn GetColumnInstance(RadGridView gridView, string uniqueName)
        {
            foreach (GridViewColumn column in gridView.Columns)
            {
                if (column.UniqueName == uniqueName)
                    return column;
            }
            return null;
        }
    }

    public class ColumnProxy
    {
        public string UniqueName { get; set; }
        public int DisplayOrder { get; set; }
        public string Header { get; set; }
        public GridViewLength Width { get; set; }
    }

    public class SortDescriptorProxy
    {
        public string ColumnUniqueName { get; set; }
        public ListSortDirection SortDirection { get; set; }
    }

    public class GroupDescriptorProxy
    {
        public string ColumnUniqueName { get; set; }
        public ListSortDirection? SortDirection { get; set; }
    }

    public class FilterDescriptorProxy
    {
        public FilterOperator Operator { get; set; }
        public object Value { get; set; }
        public bool IsCaseSensitive { get; set; }
    }

    public class FilterSetting
    {
        public string ColumnUniqueName { get; set; }
        List<object> _SelectedDistinctValues;

        public List<object> SelectedDistinctValues
        {
            get
            {
                if (_SelectedDistinctValues == null)
                {
                    _SelectedDistinctValues = new List<object>();
                }
                return _SelectedDistinctValues;
            }
        }

        FilterDescriptorProxy _Filter1;
        public FilterDescriptorProxy Filter1
        {
            get
            {
                return _Filter1;
            }
            set
            {
                _Filter1 = value;
            }
        }

        FilterDescriptorProxy _Filter2;
        public FilterDescriptorProxy Filter2
        {
            get
            {
                return _Filter2;
            }
            set
            {
                _Filter2 = value;
            }
        }
    }

    //====================================================================================
    //
    //====================================================================================
    public class RichTextBoxCustomPropertyProvider : ICustomPropertyProvider
    {
        #region ICustomPropertyProvider Members
        public CustomPropertyInfo[] GetCustomProperties()
        {
            // Create two custom properties to serialize the RichTextBox properties and content
            return new CustomPropertyInfo[]
                {
                    new CustomPropertyInfo("Content", typeof(string)),
                    new CustomPropertyInfo("AcceptsReturn", typeof(bool)),
                };
        }

        public void InitializeObject(object context)
        {

        }

        public object InitializeValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            return null;
        }

        public object ProvideValue(CustomPropertyInfo customPropertyInfo, object context)
        {
            RadRichTextBox owner = context as RadRichTextBox;
            if (customPropertyInfo.Name == "Content")
            {
                TxtFormatProvider provider = new TxtFormatProvider();
                string content = provider.Export(owner.Document);
                return content;
            }
            else
            {
                return this.GetValueSafely(customPropertyInfo.Name, owner);
            }
        }

        private object GetValueSafely(string propertyName, RadRichTextBox owner)
        {
            PropertyInfo info = owner.GetType().GetProperty(propertyName);
            if (info != null)
            {
                return info.GetValue(owner, null);
            }
            else
                throw new Exception();
        }

        private void SetValueSafely(string propertyName, object value, RadRichTextBox owner)
        {
            PropertyInfo info = owner.GetType().GetProperty(propertyName);
            if (info != null)
            {
                info.SetValue(owner, value, null);
            }
            else
                throw new Exception();
        }

        public void RestoreValue(CustomPropertyInfo customPropertyInfo, object context, object value)
        {
            RadRichTextBox owner = context as RadRichTextBox;
            if (customPropertyInfo.Name == "Content")
            {
                TxtFormatProvider provider = new TxtFormatProvider();
                owner.Document = provider.Import(value.ToString());
            }
            else
            {
                this.SetValueSafely(customPropertyInfo.Name, value, owner);
            }
        }
        #endregion
    }

    //====================================================================================
    //
    //====================================================================================
    public class PaneProxy
    {
        public object Content { get; set; }
    }
}



Thank's
0
Alex Fidanov
Telerik team
answered on 02 Apr 2012, 09:01 AM
Hi,

 I have prepared a sample project with the appropriate custom property provider and proxy classes using 2011.3.1220.35. Please let me know if you have question on the example.

Kind regards,
Alex Fidanov
the Telerik team
Sharpen your .NET Ninja skills! Attend Q1 webinar week and get a chance to win a license! Book your seat now >>
Tags
PersistenceFramework
Asked by
Oliver
Top achievements
Rank 1
Answers by
Alex Fidanov
Telerik team
Oliver
Top achievements
Rank 1
Share this question
or