#region Disclaimer / License // Copyright (C) 2014, Jackie Ng // http://trac.osgeo.org/mapguide/wiki/maestro, jumpinjackie@gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #endregion Disclaimer / License using System; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Xml; namespace OSGeo.MapGuide.ObjectModels { /// /// Inspects a resource content stream to determine the version of the resource content within /// /// The stream to be inspected is copied and the inspection is made on the copy /// public sealed class ResourceContentVersionChecker : IDisposable { private readonly XmlReader _reader; private readonly Stream _stream; /// /// Constructor /// /// The resource content stream. Inspection is done on a copy of this stream public ResourceContentVersionChecker(Stream stream) { var ms = new MemoryStream(); Utils.CopyStream(stream, ms); ms.Position = 0L; //Rewind _stream = ms; _reader = new XmlTextReader(_stream); } /// /// Alternate constructor /// /// public ResourceContentVersionChecker(string xmlContent) { _stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent)); } private ResourceTypeDescriptor _rtd; /// /// Gets the resource content version /// /// public ResourceTypeDescriptor GetVersion() { if (_rtd == null) { _rtd = GetVersionFromXmlStream(_stream); } return _rtd; } /// /// Gets the version from XML stream. /// /// The ms. /// public static ResourceTypeDescriptor GetVersionFromXmlStream(Stream ms) { string version = "1.0.0"; //NOXLATE XmlReader xr = null; try { xr = XmlReader.Create(ms); xr.MoveToContent(); if (!xr.HasAttributes) throw new SerializationException(); //Parse version number from ResourceType-x.y.z.xsd string xsd = xr.GetAttribute("xsi:noNamespaceSchemaLocation"); //NOXLATE if (xsd == null) return null; int start = (xsd.LastIndexOf("-")); //NOXLATE int end = xsd.IndexOf(".xsd") - 1; //NOXLATE version = xsd.Substring(start + 1, xsd.Length - end); string typeStr = xsd.Substring(0, start); return new ResourceTypeDescriptor(typeStr, version); } finally { xr?.Close(); xr?.Dispose(); xr = null; } } /// /// Disposes this instance /// public void Dispose() { if (_stream != null) _stream.Dispose(); if (_reader != null) _reader.Close(); } } }