// Copyright (C) Stichting Deltares 2016. All rights reserved.
//
// This file is part of Ringtoets.
//
// Ringtoets is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
//
// All names, logos, and references to "Deltares" are registered trademarks of
// Stichting Deltares and remain full property of Stichting Deltares at all times.
// All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Xml;
namespace Application.Ringtoets.Storage.Serializers
{
internal abstract class SimpleDataCollectionSerializer
{
private static readonly Type serializationRootType = typeof(TSerializedData[]);
private readonly Encoding encoding = Encoding.UTF8;
///
/// Converts the collection of to XML data.
///
/// The elements to be serialized.
/// The XML data.
/// Thrown when is null.
/// Thrown when an I/O error occurs.
/// Thrown when an error occurs during serialization.
/// Thrown when
/// contains too many objects.
public string ToXml(IEnumerable elements)
{
if (elements == null)
{
throw new ArgumentNullException("elements");
}
using (var memoryStream = new MemoryStream())
using (var writer = XmlDictionaryWriter.CreateTextWriter(memoryStream, encoding, false))
using (var streamReader = new StreamReader(memoryStream))
{
var formatter = new DataContractSerializer(serializationRootType);
formatter.WriteObject(writer, ToSerializableData(elements));
writer.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
return streamReader.ReadToEnd();
}
}
///
/// Converts XML to an array of.
///
/// The XML.
/// An array of .
/// Thrown when is null.
/// Thrown when an I/O error occurs.
/// Thrown when an error occurs during deserialization.
public TData[] FromXml(string xml)
{
if (xml == null)
{
throw new ArgumentNullException("xml");
}
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream, encoding))
{
streamWriter.Write(xml);
streamWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (var writer = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max))
{
var serializer = new DataContractSerializer(serializationRootType);
return FromSerializableData((TSerializedData[])serializer.ReadObject(writer));
}
}
}
protected abstract TSerializedData[] ToSerializableData(IEnumerable elements);
protected abstract TData[] FromSerializableData(IEnumerable serializedElements);
}
}