using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using Sleis.Validation.Spring; namespace Sleis.Models.ErrorHandling { public class CsvParserError : Exception { public Dictionary> LineErrors { get; set; } string FileName { get; set; } public CsvParserError() { LineErrors = new Dictionary>(); } public CsvParserError(string fileName) : this() { FileName = fileName; } public void AddLineError(long lineNumber, string message) { if (LineErrors.ContainsKey(lineNumber)) { LineErrors[lineNumber].Add(message); } else { LineErrors.Add(lineNumber, new List() { message}); } } public void AddLineError(long lineNumber,string columnName, string message) { if (LineErrors.ContainsKey(lineNumber)) { LineErrors[lineNumber].Add(String.Format("Column {0}: {1}", columnName, message)); } else { LineErrors.Add(lineNumber, new List() { String.Format("Column {0}: {1}", columnName, message) }); } } public bool HasErrors { get { return LineErrors.Count > 0; } } public override string Message { get { StringBuilder sb = new StringBuilder("Errors were found on the CSV File. "); foreach (long key in LineErrors.Keys.OrderBy(k=>k)) { foreach (string message in LineErrors[key]) { sb.AppendLine(String.Format("Line {0}: {1}", key, message)); } } return sb.ToString(); } } public string HtmlMessage { get { return Message.Replace(Environment.NewLine, "
"); } } public List ToRuleErrorList() { List errors = new List(); foreach (long key in LineErrors.Keys.OrderBy(k => k)) { foreach (string message in LineErrors[key]) { RuleError err = new RuleError(null, message); err.Context = String.Format("{0} Line {1}", FileName, key); errors.Add(err); } } return errors; } } }