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; }
}
}