ProcessErrorWriter
Represents a class object that writes all process errors to a CSV file. This class cannot be inherited.
using Relativity.DataExchange.Io;
using Relativity.Logging;
using System;
using System.Globalization;
using System.IO;
using System.Threading;
namespace Relativity.DataExchange.Process
{
internal sealed class ProcessErrorWriter : IProcessErrorWriter, IDisposable
{
private readonly IFileSystem fileSystem;
private readonly ILog logger;
private string errorsFile;
private IStreamWriter streamWriter;
private bool disposed;
public bool HasErrors => !string.IsNullOrEmpty(errorsFile);
public ProcessErrorWriter(IFileSystem fileSystem, ILog logger)
{
if (fileSystem == null)
throw new ArgumentNullException("fileSystem");
if (logger == null)
throw new ArgumentNullException("logger");
this.fileSystem = fileSystem;
this.logger = logger;
}
public ProcessErrorReport BuildErrorReport(CancellationToken token)
{
Close();
return new ProcessErrorReader(new IoReporterContext {
RetryOptions = RetryOptions.None
}, logger, token).ReadFile(errorsFile) as ProcessErrorReport;
}
public void Close()
{
streamWriter?.Close();
streamWriter = null;
}
public void Dispose()
{
Dispose(true);
}
public void Write(string key, string description)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
if (string.IsNullOrEmpty(description))
throw new ArgumentNullException("description");
if (string.IsNullOrEmpty(errorsFile))
errorsFile = Path.Combine(Path.GetTempPath(), $"""{Guid.NewGuid()}""");
if (streamWriter?.BaseStream == null)
streamWriter = fileSystem.CreateStreamWriter(errorsFile, false);
key = key.Replace("\"", "\"\"");
description = description.Replace("\"", "\"\"");
streamWriter.WriteLine("\"{1}{0}Error{0}{2}{0}{3}\"", "\",\"", key, description, DateTime.Now.ToString(CultureInfo.InvariantCulture));
}
private void Dispose(bool disposing)
{
if (!disposed) {
if (disposing && streamWriter != null) {
streamWriter.Close();
streamWriter = null;
}
if (!string.IsNullOrEmpty(errorsFile) && fileSystem.File.Exists(errorsFile))
fileSystem.File.Delete(errorsFile);
disposed = true;
}
}
}
}