using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using log4net; using Microsoft.Practices.ServiceLocation; using Taloyhtio.GeneralApi.Common.DTO; using Taloyhtio.GeneralApi.Common.Extensions; namespace Taloyhtio.GeneralApi.IntegrationUtility.Services.Impl { public class FileParser : IFileParser where T : class { private ILog logger = ServiceLocator.Current.GetInstance(); public List Parse(string filePath) { try { if (string.IsNullOrEmpty(filePath)) { this.logger.Warn("File path is null or empty. It won't be parsed"); return new List(); } this.logger.InfoFormat("Open file '{0}' for parsing", filePath); using (var fs = File.OpenRead(filePath)) { using (var xmlReader = new XmlTextReader(fs)) { var deserializer = new XmlSerializer(typeof(T[])); if (!deserializer.CanDeserialize(xmlReader)) { this.logger.WarnFormat("Can not deserialize file '{0}'", filePath); return new List(); } var items = deserializer.Deserialize(xmlReader) as T[]; if (items.IsNullOrEmpty()) { this.logger.Warn("Deserialization was successfull but no items were returned"); return new List(); } this.logger.InfoFormat("'{0}' item(s) were returned from the deserializer", items.Length); this.logger.InfoFormat("Close file '{0}'", filePath); return new List(items); } } } catch (Exception x) { this.logger.ErrorFormat(string.Format("{0}\n{1}", x.Message, x.StackTrace)); return new List(); } } } }