61 lines
2.2 KiB
C#
61 lines
2.2 KiB
C#
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<T> : IFileParser<T>
|
|
where T : class
|
|
{
|
|
private ILog logger = ServiceLocator.Current.GetInstance<ILog>();
|
|
|
|
public List<T> 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<T>();
|
|
}
|
|
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<T>();
|
|
}
|
|
|
|
var items = deserializer.Deserialize(xmlReader) as T[];
|
|
if (items.IsNullOrEmpty())
|
|
{
|
|
this.logger.Warn("Deserialization was successfull but no items were returned");
|
|
return new List<T>();
|
|
}
|
|
this.logger.InfoFormat("'{0}' item(s) were returned from the deserializer", items.Length);
|
|
this.logger.InfoFormat("Close file '{0}'", filePath);
|
|
return new List<T>(items);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception x)
|
|
{
|
|
this.logger.ErrorFormat(string.Format("{0}\n{1}", x.Message, x.StackTrace));
|
|
return new List<T>();
|
|
}
|
|
}
|
|
}
|
|
}
|