using CsvHelper;
using GreenTree.Strohrmann.ERP.Web.Models.Import;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace GreenTree.Strohrmann.ERP.Web.Helper
{
public static class ImportHelper
{
///
/// Checks an ImportModel instance for a valid import file for the specified data type
///
/// The data type.
/// The import model.
public static void CheckImport(ImportModel model)
{
CheckImport(model);
}
///
/// Checks an ImportModel instance for a valid import file for the specified data type
///
/// The data type.
/// The data map type.
/// The import model.
public static void CheckImport(ImportModel model)
{
if (model == null)
throw new ArgumentNullException("model", "The importModel must not be NULL.");
if (model.ImportFile == null)
throw new ArgumentException("The importModel does not contain a file.", "model");
var tempfile = Path.GetTempFileName();
using var writer = new FileStream(tempfile, FileMode.Append);
model.ImportFile.CopyTo(writer);
writer.Close();
using (var reader = new StreamReader(tempfile))
{
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
csv.Configuration.Delimiter = ";";
csv.Configuration.BadDataFound = null;
if (typeof(TEntity) != typeof(TMap))
csv.Configuration.RegisterClassMap(typeof(TMap));
csv.Read();
csv.ReadHeader();
csv.ValidateHeader();
}
}
///
/// Gets an object collection of from the import file
///
/// The data type.
/// The import model.
public static IEnumerable GetFromImport(ImportModel model)
{
return GetFromImport(model);
}
///
/// Gets an object collection of from the import file
///
/// The data type.
/// The data map type.
/// The import model.
public static IEnumerable GetFromImport(ImportModel model)
{
if (model == null)
throw new ArgumentNullException("model", "The importModel must not be NULL.");
if (model.ImportFile == null)
throw new ArgumentException("The importModel does not contain a file.", "model");
var tempfile = Path.GetTempFileName();
using var writer = new FileStream(tempfile, FileMode.Append);
model.ImportFile.CopyTo(writer);
writer.Close();
using (var reader = new StreamReader(tempfile))
{
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
csv.Configuration.Delimiter = ";";
csv.Configuration.BadDataFound = null;
if (typeof(TEntity) != typeof(TMap))
csv.Configuration.RegisterClassMap(typeof(TMap));
csv.Read();
csv.ReadHeader();
csv.ValidateHeader();
var result = csv.GetRecords().ToArray();
return result;
}
}
}
}