Skip to content

Commit

Permalink
stop relying on specific exception messages
Browse files Browse the repository at this point in the history
less linq, less string parsing. Should be more reliable
  • Loading branch information
ryepup committed May 6, 2021
1 parent 4a0ffba commit 4eb603b
Showing 1 changed file with 18 additions and 18 deletions.
36 changes: 18 additions & 18 deletions src/XlsxCompare/XlsxFacade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ namespace XlsxCompare
/// </summary>
sealed class XlsxFacade : IDisposable
{
const string DuplicateKeyPrefix = "An item with the same key has already been added. Key: ";
readonly ExcelPackage _excel;
readonly IReadOnlyDictionary<string, int> _columnMap;

Expand All @@ -22,15 +21,7 @@ sealed class XlsxFacade : IDisposable
private XlsxFacade(FileInfo file)
{
_excel = new ExcelPackage(file);
try
{
_columnMap = BuildColumnMap(Sheet);
}
catch (ArgumentException ae) when (ae.Message.StartsWith(DuplicateKeyPrefix, StringComparison.OrdinalIgnoreCase))
{
var badKey = ae.Message.Replace(DuplicateKeyPrefix, "", StringComparison.OrdinalIgnoreCase);
throw new ArgumentException($"Failed to open {file}, column headers must be unique. {file} contains duplicate column header '{badKey}'.", ae);
}
_columnMap = BuildColumnMap(Sheet);
}

/// <summary>
Expand Down Expand Up @@ -85,17 +76,26 @@ public static XlsxFacade Open(string path)
return new XlsxFacade(file);
}

static IReadOnlyDictionary<string, int> BuildColumnMap(ExcelWorksheet sheet)
=> Enumerable.Range(1, sheet.Dimension.Columns)
IReadOnlyDictionary<string, int> BuildColumnMap(ExcelWorksheet sheet)
{
var result = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var headers = Enumerable.Range(1, sheet.Dimension.Columns)
.Select(index => new
{
index,
header = sheet.Cells[1, index].Value?.ToString()
name = sheet.Cells[1, index].Value?.ToString()?.Trim()
})
.Where(x => x.header != null)
.ToDictionary(
x => x.header!.Trim(),
x => x.index,
StringComparer.OrdinalIgnoreCase);
.Where(x => x.name != null);

foreach (var header in headers)
{
if (result.ContainsKey(header.name!))
{
throw new ArgumentException($"Failed to open {_excel.File}, column headers must be unique. {_excel.File} contains duplicate column header '{header.name}'.");
}
result.Add(header.name!, header.index);
}
return result;
}
}
}

0 comments on commit 4eb603b

Please sign in to comment.