Implement serialization of Settings and SettingsRepository.

- FIX: Stile werden jetzt gespeichert.
This commit is contained in:
Daniel Kraus 2015-08-11 16:12:39 +02:00
parent 53d13b394e
commit c9fc4a5fae
21 changed files with 593 additions and 44 deletions

View File

@ -27,7 +27,7 @@ namespace Tests.Controller
[TestFixture] [TestFixture]
class SettingsRepositoryTest class SettingsRepositoryTest
{ {
SettingsRepository _savedSettings; string _savedSettings;
[SetUp] [SetUp]
public void SetUp() public void SetUp()

View File

@ -22,6 +22,7 @@ using System.Text;
using NUnit.Framework; using NUnit.Framework;
using zaaReloaded2.Controller; using zaaReloaded2.Controller;
using zaaReloaded2.Controller.Elements; using zaaReloaded2.Controller.Elements;
using System.IO;
namespace Tests.Controller namespace Tests.Controller
{ {
@ -49,5 +50,21 @@ namespace Tests.Controller
((Items)clone.Elements[1]).Content, ((Items)clone.Elements[1]).Content,
"Items content"); "Items content");
} }
[Test]
public void PersistSettings()
{
string name = "hello world";
Settings persisting = new Settings(name, new List<ElementBase>() { new Items() });
persisting.ReferenceStyle = zaaReloaded2.Formatter.ReferenceStyle.IfSpecialItem;
MemoryStream s = new MemoryStream();
persisting.Persist(s);
s.Position = 0;
Settings retrieved = Settings.Unpersist(s);
Assert.AreEqual(persisting.Name, retrieved.Name, "Name");
Assert.AreEqual(persisting.ReferenceStyle, retrieved.ReferenceStyle, "ReferenceStyle");
}
} }
} }

169
Tests/SerializationTest.cs Executable file
View File

@ -0,0 +1,169 @@
/* SelectFirstDayTest.cs
* part of zaaReloaded2
*
* Copyright 2015 Daniel Kraus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using zaaReloaded2.Controller.Elements;
using NUnit.Framework;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using zaaReloaded2.Controller;
namespace Tests.Controller
{
[TestFixture]
class SerializationTest
{
[Test]
public void SerializeControlElement()
{
SelectFirstDay element = new SelectFirstDay(
new List<FormatElementBase>()
{
new Items("hello"),
new Items("world")
}
);
MemoryStream stream = new MemoryStream();
// XmlSerializer does not work with interface properties...
// XmlSerializer serializer = new XmlSerializer(typeof(SelectFirstDay));
// BinaryFormatter serializer = new BinaryFormatter();
SoapFormatter serializer = new SoapFormatter();
serializer.Serialize(stream, element);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
Console.WriteLine(sr.ReadToEnd());
stream.Position = 0;
SelectFirstDay deserialized = serializer.Deserialize(stream) as SelectFirstDay;
Assert.IsNotNull(deserialized);
Assert.AreEqual(element.Children.Count, deserialized.Children.Count);
Assert.AreEqual(element.Children[0].Content, deserialized.Children[0].Content);
Assert.AreEqual(element.Children[1].Content, deserialized.Children[1].Content);
}
[Test]
public void SerializeFormatElement()
{
string testString = "Hello World";
CustomText element = new CustomText();
element.Content = testString;
MemoryStream stream = new MemoryStream();
SoapFormatter serializer = new SoapFormatter();
serializer.Serialize(stream, element);
stream.Position = 0;
CustomText deserialized = serializer.Deserialize(stream) as CustomText;
Assert.IsNotNull(deserialized);
Assert.AreEqual(element.Content, deserialized.Content);
}
[Test]
public void SerializeSettings()
{
Settings settings = CreateTestSettings1();
MemoryStream stream = new MemoryStream();
SoapFormatter serializer = new SoapFormatter();
serializer.Serialize(stream, settings);
stream.Position = 0;
Settings deserialized = serializer.Deserialize(stream) as Settings;
Assert.IsNotNull(deserialized);
Assert.AreEqual(settings.Name, deserialized.Name);
Assert.AreEqual(settings.ReferenceStyle, deserialized.ReferenceStyle);
Assert.AreEqual(settings.Elements.Count, deserialized.Elements.Count);
Assert.AreEqual(settings.Elements[0].GetType(), deserialized.Elements[0].GetType());
Assert.AreEqual(settings.Elements[1].GetType(), deserialized.Elements[1].GetType());
}
[Test]
public void SerializeSettingsRepository()
{
SettingsRepository repository = new SettingsRepository();
repository.SettingsList.Add(CreateTestSettings1());
repository.SettingsList.Add(CreateTestSettings2());
MemoryStream stream = new MemoryStream();
SoapFormatter serializer = new SoapFormatter();
serializer.Serialize(stream, repository);
stream.Position = 0;
SettingsRepository deserialized = serializer.Deserialize(stream) as SettingsRepository;
Assert.IsNotNull(deserialized);
Assert.AreEqual(repository.SettingsList.Count, deserialized.SettingsList.Count);
Assert.AreEqual(
repository.SettingsList[1].Elements.Count,
deserialized.SettingsList[1].Elements.Count
);
Assert.AreEqual(
repository.SettingsList[0].Name,
deserialized.SettingsList[0].Name
);
Assert.AreEqual(
repository.SettingsList[0].ReferenceStyle,
deserialized.SettingsList[0].ReferenceStyle
);
}
Settings CreateTestSettings1()
{
string testName = "test name...";
string testString = "Hello World";
SelectFirstDay controlElement = new SelectFirstDay(
new List<FormatElementBase>()
{
new Items("hello"),
new Items("world")
}
);
CustomText formatElement = new CustomText();
formatElement.Content = testString;
Settings settings = new Settings(testName, new List<ElementBase>()
{
controlElement,
formatElement
}
);
settings.ReferenceStyle = zaaReloaded2.Formatter.ReferenceStyle.IfSpecialItem;
return settings;
}
Settings CreateTestSettings2()
{
string testName = "another test name";
SelectFirstDay controlElement1 = new SelectFirstDay(
new List<FormatElementBase>()
{
new CustomText(),
}
);
SelectLastDay controlElement2 = new SelectLastDay(
new List<FormatElementBase>()
{
new Items("Items content"),
}
);
Settings settings = new Settings(testName, new List<ElementBase>()
{
controlElement1,
controlElement2
}
);
settings.ReferenceStyle = zaaReloaded2.Formatter.ReferenceStyle.IfSpecialOrAbnormal;
return settings;
}
}
}

View File

@ -58,11 +58,13 @@
<Reference Include="System.Core"> <Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework> <RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference> </Reference>
<Reference Include="System.Runtime.Serialization.Formatters.Soap" />
<Reference Include="System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Expression.Blend.Sdk.1.0.2\lib\net40-client\System.Windows.Interactivity.dll</HintPath> <HintPath>..\packages\Expression.Blend.Sdk.1.0.2\lib\net40-client\System.Windows.Interactivity.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="System.Xaml" /> <Reference Include="System.Xaml" />
<Reference Include="System.XML" />
<Reference Include="WindowsBase" /> <Reference Include="WindowsBase" />
</ItemGroup> </ItemGroup>
<Choose> <Choose>
@ -78,6 +80,7 @@
</Otherwise> </Otherwise>
</Choose> </Choose>
<ItemGroup> <ItemGroup>
<Compile Include="SerializationTest.cs" />
<Compile Include="Controller\SettingsRepositoryTest.cs" /> <Compile Include="Controller\SettingsRepositoryTest.cs" />
<Compile Include="Controller\SettingsTest.cs" /> <Compile Include="Controller\SettingsTest.cs" />
<Compile Include="Formatter\DocumentWriterTest.cs" /> <Compile Include="Formatter\DocumentWriterTest.cs" />

View File

@ -1,4 +1,5 @@
/* ControlElementBase.cs using System;
/* ControlElementBase.cs
* part of zaaReloaded2 * part of zaaReloaded2
* *
* Copyright 2015 Daniel Kraus * Copyright 2015 Daniel Kraus
@ -17,6 +18,7 @@
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
{ {
@ -24,9 +26,10 @@ namespace zaaReloaded2.Controller.Elements
/// Base class for control elements that control e.g. the working /// Base class for control elements that control e.g. the working
/// set of time points in a Formatter object. /// set of time points in a Formatter object.
/// </summary> /// </summary>
public abstract class ControlElementBase : ElementBase [Serializable]
public abstract class ControlElementBase : ElementBase, ISerializable
{ {
#region Propertis #region Properties
/// <summary> /// <summary>
/// Gets a list of child elements, all of which must be derived /// Gets a list of child elements, all of which must be derived
@ -58,6 +61,43 @@ namespace zaaReloaded2.Controller.Elements
#endregion #endregion
#region Serialization
/// <summary>
/// Deserialization constructor.
/// </summary>
protected ControlElementBase(SerializationInfo info, StreamingContext context)
{
int version = info.GetInt32("Version");
int childrenCount = info.GetInt32("ChildrenCount");
Children = new List<FormatElementBase>();
for (int i = 0; i < childrenCount; i++)
{
Type typeOfChild = info.GetValue(SerializedChildName(i, "Type"), typeof(Type)) as Type;
Children.Add(info.GetValue(SerializedChildName(i, "Object"), typeOfChild) as FormatElementBase);
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Version", Properties.Settings.Default.SerializationVersion);
info.AddValue("ChildrenCount", Children.Count);
int i = 0;
foreach (FormatElementBase child in Children)
{
info.AddValue(SerializedChildName(i, "Type"), child.GetType());
info.AddValue(SerializedChildName(i, "Object"), child);
i++;
}
}
private string SerializedChildName(int index, string info)
{
return String.Format("Child{0}{1}", index, info);
}
#endregion
#region Protected methods #region Protected methods
/// <summary> /// <summary>

View File

@ -18,6 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
@ -25,7 +26,8 @@ namespace zaaReloaded2.Controller.Elements
/// <summary> /// <summary>
/// Controller element that writes arbitrary text to the document. /// Controller element that writes arbitrary text to the document.
/// </summary> /// </summary>
class CustomText : FormatElementBase [Serializable]
public class CustomText : FormatElementBase, ISerializable
{ {
public override string Label public override string Label
{ {
@ -43,5 +45,20 @@ namespace zaaReloaded2.Controller.Elements
clone.Content = Content; clone.Content = Content;
return clone; return clone;
} }
#region Constructors
public CustomText () { }
/// <summary>
/// Deserialization constructor.
/// </summary>
protected CustomText(SerializationInfo info, StreamingContext context)
{
int version = info.GetInt32("Version");
Content = info.GetString("Content");
}
#endregion
} }
} }

View File

@ -21,13 +21,13 @@ using System.Linq;
using System.Text; using System.Text;
using Microsoft.Office.Interop.Word; using Microsoft.Office.Interop.Word;
using zaaReloaded2.LabModel; using zaaReloaded2.LabModel;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
{ {
/// <summary> /// <summary>
/// Base class for formatting elements. /// Base class for formatting elements.
/// </summary> /// </summary>
[Serializable]
public abstract class ElementBase : ICloneable public abstract class ElementBase : ICloneable
{ {
/// <summary> /// <summary>

View File

@ -16,12 +16,14 @@
* limitations under the License. * limitations under the License.
*/ */
using System;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
{ {
/// <summary> /// <summary>
/// Base class for elements that perform actual formatting. /// Base class for elements that perform actual formatting.
/// </summary> /// </summary>
public abstract class FormatElementBase : ElementBase public abstract class FormatElementBase : ElementBase, ISerializable
{ {
/// <summary> /// <summary>
/// Gets or sets the content of this format element. /// Gets or sets the content of this format element.
@ -41,5 +43,15 @@ namespace zaaReloaded2.Controller.Elements
protected virtual void OnContentChanged() {} protected virtual void OnContentChanged() {}
private string _content; private string _content;
#region Serialization
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Version", Properties.Settings.Default.SerializationVersion);
info.AddValue("Content", Content);
}
#endregion
} }
} }

View File

@ -23,6 +23,7 @@ using System.Diagnostics;
using Microsoft.Office.Interop.Word; using Microsoft.Office.Interop.Word;
using zaaReloaded2.LabModel; using zaaReloaded2.LabModel;
using zaaReloaded2.Formatter; using zaaReloaded2.Formatter;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
{ {
@ -31,7 +32,7 @@ namespace zaaReloaded2.Controller.Elements
/// to a Word document. /// to a Word document.
/// </summary> /// </summary>
[Serializable] [Serializable]
class Items : CustomText public class Items : CustomText
{ {
#region ElementBase implementation #region ElementBase implementation
@ -93,6 +94,13 @@ namespace zaaReloaded2.Controller.Elements
Content = content; Content = content;
} }
/// <summary>
/// Deserialization constructor.
/// </summary>
protected Items(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion #endregion
#region Private methods #region Private methods

View File

@ -18,6 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
@ -26,7 +27,8 @@ namespace zaaReloaded2.Controller.Elements
/// Format element that causes a Formatter object to move the /// Format element that causes a Formatter object to move the
/// insertion point to the next colum in a layout table. /// insertion point to the next colum in a layout table.
/// </summary> /// </summary>
class NextColumn : ControlElementBase [Serializable]
public class NextColumn : ControlElementBase, ISerializable
{ {
public override string Label public override string Label
{ {
@ -50,5 +52,18 @@ namespace zaaReloaded2.Controller.Elements
{ {
return new NextColumn(); return new NextColumn();
} }
#region Constructors
public NextColumn() : base() { }
/// <summary>
/// Deserialization constructor.
/// </summary>
protected NextColumn(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
} }
} }

View File

@ -18,11 +18,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
{ {
class SelectEachDay : ControlElementBase [Serializable]
public class SelectEachDay : ControlElementBase
{ {
public override string Label public override string Label
{ {
@ -34,6 +36,13 @@ namespace zaaReloaded2.Controller.Elements
formatter.ProcessEachDay(this); formatter.ProcessEachDay(this);
} }
protected override ElementBase CreateInstance()
{
return new SelectEachDay(CloneChildren());
}
#region Constructors
public SelectEachDay() : base() { } public SelectEachDay() : base() { }
public SelectEachDay(FormatElementBase formatElement) public SelectEachDay(FormatElementBase formatElement)
@ -44,9 +53,13 @@ namespace zaaReloaded2.Controller.Elements
: base(formatElements) : base(formatElements)
{ } { }
protected override ElementBase CreateInstance() /// <summary>
{ /// Deserialization constructor.
return new SelectEachDay(CloneChildren()); /// </summary>
} protected SelectEachDay(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
} }
} }

View File

@ -18,6 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
@ -26,7 +27,8 @@ namespace zaaReloaded2.Controller.Elements
/// Selects the time points of the first day in a given Formatter /// Selects the time points of the first day in a given Formatter
/// object. /// object.
/// </summary> /// </summary>
class SelectFirstDay : ControlElementBase [Serializable]
public class SelectFirstDay : ControlElementBase, ISerializable
{ {
public override string Label public override string Label
{ {
@ -38,6 +40,13 @@ namespace zaaReloaded2.Controller.Elements
formatter.ProcessFirstDay(this); formatter.ProcessFirstDay(this);
} }
protected override ElementBase CreateInstance()
{
return new SelectFirstDay(CloneChildren());
}
#region Constructors
public SelectFirstDay() : base() { } public SelectFirstDay() : base() { }
public SelectFirstDay(FormatElementBase formatElement) public SelectFirstDay(FormatElementBase formatElement)
@ -48,9 +57,13 @@ namespace zaaReloaded2.Controller.Elements
: base(formatElements) : base(formatElements)
{ } { }
protected override ElementBase CreateInstance() /// <summary>
{ /// Deserialization constructor.
return new SelectFirstDay(CloneChildren()); /// </summary>
} protected SelectFirstDay(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
} }
} }

View File

@ -19,6 +19,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
@ -27,7 +28,8 @@ namespace zaaReloaded2.Controller.Elements
/// Selects the time points of the last day in a given Formatter /// Selects the time points of the last day in a given Formatter
/// object. /// object.
/// </summary> /// </summary>
class SelectLastDay : ControlElementBase [Serializable]
public class SelectLastDay : ControlElementBase, ISerializable
{ {
public override string Label public override string Label
{ {
@ -39,6 +41,13 @@ namespace zaaReloaded2.Controller.Elements
formatter.ProcessLastDay(this); formatter.ProcessLastDay(this);
} }
protected override ElementBase CreateInstance()
{
return new SelectLastDay(CloneChildren());
}
#region Constructors
public SelectLastDay() : base() { } public SelectLastDay() : base() { }
public SelectLastDay(FormatElementBase formatElement) public SelectLastDay(FormatElementBase formatElement)
@ -49,9 +58,13 @@ namespace zaaReloaded2.Controller.Elements
: base(formatElements) : base(formatElements)
{ } { }
protected override ElementBase CreateInstance() /// <summary>
{ /// Deserialization constructor.
return new SelectLastDay(CloneChildren()); /// </summary>
} protected SelectLastDay(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
} }
} }

View File

@ -18,6 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace zaaReloaded2.Controller.Elements namespace zaaReloaded2.Controller.Elements
@ -26,7 +27,8 @@ namespace zaaReloaded2.Controller.Elements
/// Format element that causes a Formatter object to insert a table with /// Format element that causes a Formatter object to insert a table with
/// two columns and one row into the documents. /// two columns and one row into the documents.
/// </summary> /// </summary>
class TwoColumns : ControlElementBase [Serializable]
public class TwoColumns : ControlElementBase, ISerializable
{ {
public override string Label public override string Label
{ {
@ -50,5 +52,18 @@ namespace zaaReloaded2.Controller.Elements
{ {
return new TwoColumns(); return new TwoColumns();
} }
#region Constructors
public TwoColumns() : base() { }
/// <summary>
/// Deserialization constructor.
/// </summary>
protected TwoColumns(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endregion
} }
} }

View File

@ -21,6 +21,9 @@ using System.Linq;
using System.Text; using System.Text;
using zaaReloaded2.Formatter; using zaaReloaded2.Formatter;
using zaaReloaded2.Controller.Elements; using zaaReloaded2.Controller.Elements;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller namespace zaaReloaded2.Controller
{ {
@ -28,8 +31,43 @@ namespace zaaReloaded2.Controller
/// Holds settings related to controlling laboratory output. /// Holds settings related to controlling laboratory output.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class Settings : ICloneable public class Settings : ICloneable, ISerializable
{ {
#region Persistence
/// <summary>
/// Custom serialization method that writes this settings
/// to a human-readable text file.
/// </summary>
/// <param name="stream"></param>
public void Persist(Stream stream)
{
StreamWriter w = new StreamWriter(stream);
w.WriteLine(String.Format("[{0}]", Name));
w.WriteLine(ReferenceStyle.ToString());
w.Flush();
}
public static Settings Unpersist(Stream stream)
{
StreamReader r = new StreamReader(stream);
string line = r.ReadLine();
Match m = _persistenceHeaderRegex.Match(line);
if (!m.Success)
throw new InvalidDataException("Settings header line does not match expected format.");
Settings settings = new Settings();
settings.Name = m.Groups["name"].Value;
line = r.ReadLine();
settings.ReferenceStyle = (ReferenceStyle)Enum.Parse(typeof(ReferenceStyle), line);
return settings;
}
#endregion
#region Properties #region Properties
/// <summary> /// <summary>
@ -94,6 +132,39 @@ namespace zaaReloaded2.Controller
} }
} }
/// <summary>
/// Creates a new Settings object with an initial
/// set of elements, a name, and a unique ID.
/// </summary>
/// <param name="initialElements">Set of ElementBase
/// object (or derived ones).</param>
/// <param name="name">Name of these settings.</param>
/// <param name="Uid">Unique ID for this Settings object.</param>
public Settings(string name, IList<ElementBase> initialElements, Guid uid)
: this(name, initialElements)
{
Uid = uid;
}
/// <summary>
/// Deserialization constructor.
/// </summary>
protected Settings(SerializationInfo info, StreamingContext context)
{
int version = info.GetInt32("Version");
Uid = (Guid)info.GetValue("Uid", typeof(Guid));
Name = info.GetString("Name");
ReferenceStyle = (ReferenceStyle)info.GetValue("ReferenceStyle", typeof(ReferenceStyle));
int elementsCount = info.GetInt32("ElementsCount");
Elements = new List<ElementBase>();
for (int i = 0; i < elementsCount; i++)
{
Type type = info.GetValue(SerializationElementName(i, "Type"), typeof(Type)) as Type;
ElementBase element = info.GetValue(SerializationElementName(i, "Object"), type) as ElementBase;
Elements.Add(element);
}
}
#endregion #endregion
#region Public methods #region Public methods
@ -122,5 +193,37 @@ namespace zaaReloaded2.Controller
} }
#endregion #endregion
#region Implementation of ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Version", Properties.Settings.Default.SerializationVersion);
info.AddValue("Uid", Uid);
info.AddValue("Name", Name);
info.AddValue("ReferenceStyle", ReferenceStyle);
info.AddValue("ElementsCount", Elements.Count);
int i = 0;
foreach (ElementBase e in Elements)
{
info.AddValue(SerializationElementName(i, "Type"), e.GetType());
info.AddValue(SerializationElementName(i, "Object"), e);
i++;
}
}
string SerializationElementName(int index, string info)
{
return String.Format("Element{0}{1}", index, info);
}
#endregion
#region Fields
// Defines header lines for the persistence file: "[My name]" and so on.
static readonly Regex _persistenceHeaderRegex = new Regex(@"^\[(?<name>.+?)]$");
#endregion
} }
} }

View File

@ -18,10 +18,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Configuration; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Xml.Serialization;
using System.Reflection;
using zaaReloaded2.Controller.Elements; using zaaReloaded2.Controller.Elements;
using System.Runtime.Serialization.Formatters.Soap;
using System.Web;
using System.Runtime.Serialization;
namespace zaaReloaded2.Controller namespace zaaReloaded2.Controller
{ {
@ -35,30 +40,45 @@ namespace zaaReloaded2.Controller
/// different from zaaReloaded's Settings. /// different from zaaReloaded's Settings.
/// </remarks> /// </remarks>
[Serializable] [Serializable]
public class SettingsRepository : ApplicationSettingsBase public class SettingsRepository : ISerializable
{ {
#region Persistence #region Properties persistence
public static SettingsRepository Load() public static SettingsRepository Load()
{ {
return string s = Properties.Settings.Default.SettingsRepository;
zaaReloaded2.Properties.Settings.Default.SettingsRepository ?? if (String.IsNullOrEmpty(s))
new SettingsRepository(); {
return null;
}
else
{
MemoryStream stream = new MemoryStream();
string encoded = Properties.Settings.Default.SettingsRepository;
byte[] bytes = Convert.FromBase64String(encoded);
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0;
SoapFormatter serializer = new SoapFormatter();
return serializer.Deserialize(stream) as SettingsRepository;
}
} }
public void Store() public void Store()
{ {
zaaReloaded2.Properties.Settings.Default.SettingsRepository = this; MemoryStream stream = new MemoryStream();
zaaReloaded2.Properties.Settings.Default.Save(); SoapFormatter serializer = new SoapFormatter();
serializer.Serialize(stream, this);
stream.Position = 0;
string encoded = Convert.ToBase64String(stream.ToArray());
Properties.Settings.Default.SettingsRepository = encoded;
Properties.Settings.Default.Save();
} }
#endregion #endregion
#region Properties #region Properties
[UserScopedSetting()] public IList<Settings> SettingsList { get; protected set; }
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
public IList<Settings> SettingsList { get; private set; }
#endregion #endregion
@ -76,6 +96,41 @@ namespace zaaReloaded2.Controller
#endregion #endregion
#region Serialization
protected SettingsRepository(SerializationInfo info, StreamingContext context)
{
int version = info.GetInt32("Version");
int settingsCount = info.GetInt32("SettingsCount");
SettingsList = new List<Settings>();
for (int i = 0; i < settingsCount; i++)
{
Type type = info.GetValue(SerializationSettingsName(i, "Type"), typeof(Type)) as Type;
Settings s = info.GetValue(SerializationSettingsName(i, "Object"), typeof(Settings)) as Settings;
SettingsList.Add(s);
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Version", Properties.Settings.Default.SerializationVersion);
info.AddValue("SettingsCount", SettingsList.Count);
int i = 0;
foreach (Settings s in SettingsList)
{
info.AddValue(SerializationSettingsName(i, "Type"), s.GetType());
info.AddValue(SerializationSettingsName(i, "Object"), s);
i++;
}
}
string SerializationSettingsName(int index, string info)
{
return String.Format("Settings{0}{1}", index, info);
}
#endregion
#region Public methods #region Public methods
/// <summary> /// <summary>
@ -90,6 +145,27 @@ namespace zaaReloaded2.Controller
return SettingsList.FirstOrDefault(s => s.Uid == uid); return SettingsList.FirstOrDefault(s => s.Uid == uid);
} }
/// <summary>
/// Imports one Settings object by deserialization
/// from a stream.
/// </summary>
/// <param name="s">Stream to read from.</param>
/// <returns>True if the import was successful.</returns>
bool Import(Stream s)
{
XmlSerializer ser = new XmlSerializer(typeof(Settings));
Settings settings = ser.Deserialize(s) as Settings;
if (settings != null)
{
SettingsList.Add(settings);
return true;
}
else
{
return false;
}
}
#endregion #endregion
#region Private methods #region Private methods
@ -132,7 +208,8 @@ namespace zaaReloaded2.Controller
new SelectFirstDay(defaultItems), new SelectFirstDay(defaultItems),
new NextColumn(), new NextColumn(),
new SelectLastDay(defaultItems) new SelectLastDay(defaultItems)
} },
Guid.Parse(DEFAULT_SETTINGS_1_UID)
) )
); );
@ -143,11 +220,26 @@ namespace zaaReloaded2.Controller
new List<ElementBase>() new List<ElementBase>()
{ {
new SelectEachDay(defaultItems), new SelectEachDay(defaultItems),
} },
Guid.Parse(DEFAULT_SETTINGS_2_UID)
) )
); );
} }
#endregion #endregion
#region Private constants
/// <summary>
/// Constant GUID for the first default Settings.
/// </summary>
const string DEFAULT_SETTINGS_1_UID = "EA79DE6C-E999-44F1-9122-929A8AA404CB";
/// <summary>
/// Constant GUID for the second default Settings.
/// </summary>
const string DEFAULT_SETTINGS_2_UID = "783C63B5-A964-4368-B2D0-D4595DCCB952";
#endregion
} }
} }

View File

@ -26,7 +26,6 @@ namespace zaaReloaded2.Formatter
/// <summary> /// <summary>
/// Describes the style of normal range references. /// Describes the style of normal range references.
/// </summary> /// </summary>
[Serializable]
public enum ReferenceStyle public enum ReferenceStyle
{ {
/// <summary> /// <summary>

View File

@ -25,9 +25,10 @@ namespace zaaReloaded2.Properties {
[global::System.Configuration.UserScopedSettingAttribute()] [global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::zaaReloaded2.Controller.SettingsRepository SettingsRepository { [global::System.Configuration.DefaultSettingValueAttribute("")]
public string SettingsRepository {
get { get {
return ((global::zaaReloaded2.Controller.SettingsRepository)(this["SettingsRepository"])); return ((string)(this["SettingsRepository"]));
} }
set { set {
this["SettingsRepository"] = value; this["SettingsRepository"] = value;
@ -281,5 +282,14 @@ namespace zaaReloaded2.Properties {
return ((string)(this["ControlElementLabel"])); return ((string)(this["ControlElementLabel"]));
} }
} }
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1")]
public int SerializationVersion {
get {
return ((int)(this["SerializationVersion"]));
}
}
} }
} }

View File

@ -2,7 +2,7 @@
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="zaaReloaded2.Properties" GeneratedClassName="Settings"> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="zaaReloaded2.Properties" GeneratedClassName="Settings">
<Profiles /> <Profiles />
<Settings> <Settings>
<Setting Name="SettingsRepository" Type="zaaReloaded2.Controller.SettingsRepository" Scope="User"> <Setting Name="SettingsRepository" Type="System.String" Scope="User">
<Value Profile="(Default)" /> <Value Profile="(Default)" />
</Setting> </Setting>
<Setting Name="AddinName" Type="System.String" Scope="Application"> <Setting Name="AddinName" Type="System.String" Scope="Application">
@ -86,5 +86,8 @@
<Setting Name="ControlElementLabel" Type="System.String" Scope="Application"> <Setting Name="ControlElementLabel" Type="System.String" Scope="Application">
<Value Profile="(Default)">Steuerungs-Elemente</Value> <Value Profile="(Default)">Steuerungs-Elemente</Value>
</Setting> </Setting>
<Setting Name="SerializationVersion" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">1</Value>
</Setting>
</Settings> </Settings>
</SettingsFile> </SettingsFile>

View File

@ -104,10 +104,16 @@
<setting name="ControlElementLabel" serializeAs="String"> <setting name="ControlElementLabel" serializeAs="String">
<value>Steuerungs-Elemente</value> <value>Steuerungs-Elemente</value>
</setting> </setting>
<setting name="SerializationVersion" serializeAs="String">
<value>1</value>
</setting>
</zaaReloaded2.Properties.Settings> </zaaReloaded2.Properties.Settings>
</applicationSettings> </applicationSettings>
<userSettings> <userSettings>
<zaaReloaded2.Properties.Settings> <zaaReloaded2.Properties.Settings>
<setting name="SettingsRepository" serializeAs="String">
<value />
</setting>
<setting name="LastUpdateCheck" serializeAs="String"> <setting name="LastUpdateCheck" serializeAs="String">
<value /> <value />
</setting> </setting>

View File

@ -143,6 +143,7 @@
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Runtime.Serialization.Formatters.Soap" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Reference Include="System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Expression.Blend.Sdk.1.0.2\lib\net40-client\System.Windows.Interactivity.dll</HintPath> <HintPath>..\packages\Expression.Blend.Sdk.1.0.2\lib\net40-client\System.Windows.Interactivity.dll</HintPath>