ProcessEventWriter
Represents an abstract object that writes output events to a file. This class cannot be inherited.
using Relativity.DataExchange.Io;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Relativity.DataExchange.Process
{
internal sealed class ProcessEventWriter : IProcessEventWriter, IDisposable
{
private readonly IFileSystem fileSystem;
private readonly XmlSerializer serializer;
private IStreamWriter streamWriter;
private bool disposed;
public string File { get; set; }
public bool HasEvents => !string.IsNullOrEmpty(File);
public ProcessEventWriter(IFileSystem fileSystem)
{
if (fileSystem == null)
throw new ArgumentNullException("fileSystem");
this.fileSystem = fileSystem;
File = null;
streamWriter = null;
disposed = false;
serializer = new XmlSerializer(typeof(ProcessEventDto));
}
public void Close()
{
streamWriter?.Close();
streamWriter = null;
}
public void Dispose()
{
Dispose(true);
}
public void Save(string targetFile)
{
if (string.IsNullOrEmpty(targetFile))
throw new ArgumentNullException("targetFile");
if (!string.IsNullOrEmpty(File) && fileSystem.File.Exists(File))
fileSystem.File.Move(File, targetFile);
}
public void Write(ProcessEventDto dto)
{
if (dto == null)
throw new ArgumentNullException("dto");
if (string.IsNullOrEmpty(File))
File = Path.Combine(Path.GetTempPath(), $"""{Guid.NewGuid()}""");
if (streamWriter?.BaseStream == null)
streamWriter = fileSystem.CreateStreamWriter(File, false);
serializer.Serialize(streamWriter.BaseStream, dto);
}
private void Dispose(bool disposing)
{
if (!disposed) {
if (disposing) {
if (streamWriter != null) {
streamWriter.Close();
streamWriter = null;
}
if (!string.IsNullOrEmpty(File) && fileSystem.File.Exists(File))
fileSystem.File.Delete(File);
}
disposed = true;
}
}
}
}