public UnitOfWork() { _context = new ObservationDbContext(); ContractService = new ContractService(_context); ObservationService = new ObservationService(_context); ObservationExportService = new ObservationExportService(_context); }
/// <summary> /// Will export anything that hasn't yet been exported. This can be constituted by <see cref="Observation.IsExported"/> /// that tracks if the observation has been exported. We can then export at /// any time of the day and only export new ones in this case. /// </summary> public void Export() { var observations = GetAllForExport().ToList(); if (!observations.Any()) { //Don't send any emails etc, nothing to send. return; } IEnumerable <ObservationExport> observationsExportData = observations .Select(observation => new ObservationExport { //Map to domain object so we have a bit more information Observation = Mapper.Map <Observation>(observation), //Inject custom properties here for export that can't be retrieved //by the main data query. AbsoluteUrl = ObservationService.GetAbsoluteUrl(observation.FilePath) }); using (var memoryStream = new MemoryStream()) using (var textWriter = new StreamWriter(memoryStream)) using (var csvWriter = new CsvWriter(textWriter)) { csvWriter.Configuration.RegisterClassMap <ObservationExportCsvMap>(); //Use WriteRecords rather than a single WriteRecord as it doesn't seem to add //header rows for some reason? Presumably because you are only writing a single //item at a time? csvWriter.WriteRecords((IEnumerable)observationsExportData); //Flush the buffer and seek back to the start for output. textWriter.Flush(); memoryStream.Position = 0; SendEmail(memoryStream); } //Mark the records as exported now that we have "exported" the list. foreach (var observation in observations) { observation.IsExported = true; } _context.SaveChanges(); }