Exemplo n.º 1
0
        public void write_csv_writes_all_public_properties_by_default()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                var items = new TestType1[]
                {
                    new TestType1
                    {
                        Property1 = "1",
                        Property2 = "2",
                        Property3 = "3"
                    },
                    new TestType1
                    {
                        Property1 = "4",
                        Property2 = "5",
                        Property3 = "6"
                    }
                };

                items.WriteCsv(writer);
                var result = stringWriter.ToString();

                // can't assert exact contents because order of properties is undefined (and changes)
                Assert.Contains("Property1", result);
                Assert.Contains("Property2", result);
                Assert.Contains("1", result);
                Assert.Contains("2", result);
                Assert.Contains("4", result);
                Assert.Contains("5", result);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Экспортирует массив данных в CSV формат с учетом выбранной локали
        /// </summary>
        /// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
        /// <param name="localisation">Локализация</param>
        /// <returns>Успешное завершение операции</returns>
        public override bool Export(String path, Localisation localisation)
        {
            try
            {
                if (!path.EndsWith(".csv"))
                    path += ".csv";

                Thread.CurrentThread.CurrentCulture = new CultureInfo((int)localisation);

                log.Info(String.Format("Export to .csv file to: {0}", path));
                var timer = new Stopwatch();
                timer.Start();

                using (var streamWriter = new StreamWriter(path))
                using (var writer = new CsvWriter(streamWriter))
                {
                    writer.ValueSeparator = Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator[0];
                    dataTable.WriteCsv(writer);
                }

                timer.Stop();
                log.Info(String.Format("CSV export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Can't export to .csv file!", ex);
                return false;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converts a DataTable to a csv string
        /// </summary>
        /// <param name="dataTable">The dataTable</param>
        /// <param name="headers">(Optional) Headers</param>
        /// <param name="ignore">(Optional) Keys to ignore</param>
        public static string ToCSV(this IEnumerable<Dictionary<string, Object>> dataTable, string[] headers = null, string[] ignore = null)
        {
            if (ignore == null)
                ignore = new string[] { };

            var stringWriter = new StringWriter();
            var csvWriter = new CsvWriter(stringWriter);

            if (headers == null)
            {
                headers = (from kvp in dataTable.First()
                           where !ignore.Contains(kvp.Key)
                           select kvp.Key).ToArray();
            }

            csvWriter.WriteHeaderRecord(headers);

            foreach (var record in dataTable)
            {
                var values = (from kvp in record
                              where !ignore.Contains(kvp.Key)
                              select  kvp.Value == null? "":
                              kvp.Value.ToString()).ToArray();

                csvWriter.WriteDataRecord(values);
            }
            csvWriter.Close();

            var csv = stringWriter.ToString();
            return csv;
        }
Exemplo n.º 4
0
        public static void WriteTable(TableFileBase tableFile)
        {
            string path = "./Assets/Resources/Tables/" + tableFile.GetType().Name + ".csv";
            string[] lines = File.ReadAllLines(path, Encoding.Default);
            lines[0] = lines[0].Replace("\r\n", "\n");

            StringReader rdr = new StringReader(string.Join("\n", lines));
            List<string> titles = new List<string>();
            using (var reader = new CsvReader(rdr))
            {
                HeaderRecord header = reader.ReadHeaderRecord();
                for (int i = 0; i < header.Count; ++i)
                {
                    titles.Add(header[i]);
                }
            }

            File.Delete(path);

            using (StreamWriter SourceStream = new StreamWriter(path, false, System.Text.Encoding.Default))
            {
                CsvWriter writer = new CsvWriter(SourceStream);
                writer.WriteRecord(titles.ToArray());
                foreach (var record in tableFile.Records)
                {
                    writer.WriteRecord(record.Value.GetRecordStr());
                }
            }
        }
Exemplo n.º 5
0
        public void write_csv_writes_header_record_by_default()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                new TestType1[0].WriteCsv(writer);
                var result = stringWriter.ToString();

                // can't assert exact contents because order of properties is undefined (and changes)
                Assert.Contains("Property1", result);
                Assert.Contains("Property2", result);
            }
        }
Exemplo n.º 6
0
        public static void ExportCSV(string path, Guid pollId)
        {
            var poll = DataService.PerThread.ContentSet.OfType<Poll>().SingleOrDefault(x => x.Id == pollId);
            if (poll == null)
            {
                throw new BusinessLogicException("Указан неверный идентификатор голосования");
            }
            else
            {
                var bulletins = poll.Bulletins.OrderByDescending(x => x.Weight).ThenByDescending(x => x.Result).ThenBy(x => x.Id).ToList();
                using (var writer = new CsvWriter(path))
                {
                    writer.ValueSeparator = ';';
                    writer.WriteHeaderRecord("Номер бюллетеня", "Голос", "Вес");

                    foreach (var pollBulletin in bulletins)
                    {
                        if (pollBulletin.Weight.Equals(0))
                        {
                            writer.WriteDataRecord(pollBulletin.Id, "Голос делегирован", "-");
                        }
                        else
                        {

                            switch ((VoteOption)pollBulletin.Result)
                            {
                                case VoteOption.Yes:
                                    writer.WriteDataRecord(pollBulletin.Id, "За", pollBulletin.Weight);
                                    break;
                                case VoteOption.No:
                                    writer.WriteDataRecord(pollBulletin.Id, "Против", pollBulletin.Weight);
                                    break;
                                case VoteOption.NotVoted:
                                    writer.WriteDataRecord(pollBulletin.Id, "Не голосовал", pollBulletin.Weight);
                                    break;
                                case VoteOption.Refrained:
                                    writer.WriteDataRecord(pollBulletin.Id, "Воздержался", pollBulletin.Weight);
                                    break;
                                default:
                                    writer.WriteDataRecord(pollBulletin.Id, "Неизвестно", pollBulletin.Weight);
                                    break;
                            }
                        }
                    }
                    writer.Close();
                }
            }
        }
Exemplo n.º 7
0
        protected override void ProcessRecord()
        {
            FileName = Path.GetFullPath(FileName);
            var basePath = Path.GetDirectoryName(FileName);
            var csvName = string.Format("{0}.csv", Path.GetFileNameWithoutExtension(FileName));

            if (File.Exists(FileName)) { throw new ArgumentException(string.Format("File {0} exists!", FileName));}
            if (!Directory.Exists(basePath)) { throw new DirectoryNotFoundException(string.Format("Directory {0} does not exist.", basePath));}
            
            using (var zipStream = new ZipFile(basePath))
            using (var csvRaw = new MemoryStream())
            using (var csvWriter = new CsvWriter(csvRaw))
            {
                csvWriter.WriteAll(Data);
                csvRaw.Seek(0, SeekOrigin.Begin);
                zipStream.AddEntry(csvName, csvRaw);
            }
        }
Exemplo n.º 8
0
        public override void Execute(object parameter)
        {
            var stream = GetOutputStream();

            if (stream == null)
                return;

             using (stream)
             using (var writer = new CsvWriter(stream))
             {
                 writer.WriteHeaderRecord(new[] {"Key"}.Concat(model.ValueCalculations.Select(v => v.Header)));

                 foreach (var reportRow in model.Results)
                 {
                     writer.WriteDataRecord(new object[] { reportRow.Key}.Concat(model.ValueCalculations.Select(v => (object)reportRow.Values[v.Header])));
                 }
             }
        }
Exemplo n.º 9
0
        private static void Main()
        {
            if (Settings.Default.UseAccessPair)
            {
                _tokens.AccessToken = Settings.Default.AccessToken;
                _tokens.AccessTokenSecret = Settings.Default.AccessSecret;
            }
            else
            {
                if (string.IsNullOrEmpty(Settings.Default.UserAccessToken) || string.IsNullOrEmpty(Settings.Default.UserAccessSecret))
                {
                    var tokenResponse = GetUserToken();
                    Settings.Default.UserAccessToken = tokenResponse.Token;
                    Settings.Default.UserAccessSecret = tokenResponse.TokenSecret;
                    Settings.Default.UserId = (int)tokenResponse.UserId;
                    Settings.Default.Save();
                }
                _tokens.AccessToken = Settings.Default.UserAccessToken;
                _tokens.AccessTokenSecret = Settings.Default.UserAccessSecret;
            }

            /*
            {
                var userInfo = GetUserInfo().ToBsonDocument();
                var csvWriter = new CsvWriter(Console.Out);
                csvWriter.WriteHeaderRecord(userInfo.Names.ToArray());
                csvWriter.WriteDataRecord(userInfo.Values);
                Console.WriteLine();
            }
            */
            {
                var users = GetMutualFriends(_tokens);
                var csvWriter = new CsvWriter(Console.Out);
                csvWriter.WriteHeaderRecord(users.First().ToBsonDocument().Names.ToArray());
                foreach (var user in users) { csvWriter.WriteDataRecord(user.ToBsonDocument().Values.ToArray()); }
                Console.WriteLine();
            }
        }
Exemplo n.º 10
0
        public static void WriteFile(ContentFile file)
        {
            if (!string.IsNullOrEmpty(file.ConstructFile.OldName))
            {
                string oldPath = TableGlobalConfig.Instance.ResTablePath + "/" + file.ConstructFile.OldName + ".csv";
                if (!string.IsNullOrEmpty(oldPath))
                {
                    File.Delete(oldPath);
                }
                file.WriteFlag = true;

                WriteConstruct.WriteFileOldName(file.ConstructFile, "");
            }

            if(!file.IsNeedWrite())
                return;

            string path = TableGlobalConfig.Instance.ResTablePath + "/" + file.ConstructFile.Name + ".csv";
            if (string.IsNullOrEmpty(path))
                return;

            File.Delete(path);

            using (StreamWriter SourceStream = new StreamWriter(path, false, System.Text.Encoding.UTF8))
            {
                CsvWriter writer = new CsvWriter(SourceStream);
                writer.WriteRecord(file.ConstructFile.GetColumnTitles());
                foreach (ContentRow row in file.ContentRow)
                {
                    writer.WriteRecord(row.GetItemsStr());
                }
            }

            file.AlreadyWrite();

        }
Exemplo n.º 11
0
 public void write_csv_throws_if_any_property_cannot_be_resolved()
 {
     var writer = new CsvWriter(new StringWriter());
     var ex = Assert.Throws<InvalidOperationException>(() => new List<DateTime>().WriteCsv(writer, true, new string[] { "Date", "Foo" }));
     Assert.Equal("Property 'Foo' was not found on type 'System.DateTime'.", ex.Message);
 }
Exemplo n.º 12
0
 public async Task write_csv_async_throws_if_enumerable_is_null()
 {
     var writer = new CsvWriter(new StringWriter());
     await Assert.ThrowsAsync<ArgumentNullException>(() => ((IEnumerable<DateTime>)null).WriteCsvAsync(writer));
 }
Exemplo n.º 13
0
 public async Task write_csv_async_throws_if_property_names_is_null()
 {
     var writer = new CsvWriter(new StringWriter());
     await Assert.ThrowsAsync<ArgumentNullException>(() => new List<DateTime>().WriteCsvAsync(writer, true, null));
 }
Exemplo n.º 14
0
        public async Task write_csv_async_non_reflection_overload_allows_arbitrary_conversion_of_objects_to_csv()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                var items = new DateTime[]
                {
                    new DateTime(2004, 12, 31),
                    new DateTime(1978, 12, 4),
                    new DateTime(1979, 10, 26)
                };

                var header = new string[] { "The Year", "Even Year?" };
                await items.WriteCsvAsync(writer, header, dt => new string[] { dt.Year.ToString(CultureInfo.InvariantCulture), (dt.Year % 2 == 0).ToString(CultureInfo.InvariantCulture) });
                Assert.Equal("The Year,Even Year?<EOL>2004,True<EOL>1978,True<EOL>1979,False<EOL>", stringWriter.ToString());
            }
        }
Exemplo n.º 15
0
 public void write_csv_throws_if_csv_writer_is_disposed()
 {
     var writer = new CsvWriter(new StringWriter());
     writer.Dispose();
     Assert.Throws<ObjectDisposedException>(() => new DateTime[0].WriteCsv(writer));
 }
Exemplo n.º 16
0
 public async Task write_csv_async_non_reflection_throws_if_object_to_record_converter_is_null()
 {
     using (var writer = new CsvWriter(new StringWriter()))
     {
         var header = new string[] { "The Year", "Even Year?" };
         await Assert.ThrowsAsync<ArgumentNullException>(() => new DateTime[0].WriteCsvAsync(writer, header, null));
     }
 }
Exemplo n.º 17
0
 public void write_csv_throws_if_any_property_name_is_null()
 {
     var writer = new CsvWriter(new StringWriter());
     var ex = Assert.Throws<ArgumentException>(() => new List<DateTime>().WriteCsv(writer, true, new string[] { "Date", null }));
     Assert.Equal("A property name is null.", ex.Message);
 }
Exemplo n.º 18
0
        /// <summary>
        /// Сохраняет DataGridView в CSV в файл с указанным именем.
        /// </summary>
        /// <param name="dgvInf">Таблица DataGridView</param>
        /// <param name="filename">Имя файла</param>
        public static void DGVtoCSV(DataGridView dgvInf, string filename)
        {
            using (CsvWriter writer = new CsvWriter(filename))
            {
                writer.ValueSeparator = Char.Parse(";");

                string[] dataString = new string[dgvInf.ColumnCount];

                for (int i = 0; i < dgvInf.RowCount; i++)
                {
                    for (int b = 0; b < dgvInf.ColumnCount; b++)
                    {
                        dataString[b] = dgvInf.Rows[i].Cells[b].Value.ToString();
                    }
                    writer.WriteDataRecord(dataString);
                }

                writer.Close();
            }
        }
 private void WriteColumnsForDocuments(CsvWriter writer, IEnumerable<JsonDocument> documents, DocumentColumnsExtractor extractor)
 {
     foreach (var document in documents)
     {
         var values = extractor.GetValues(document);
         writer.WriteDataRecord(values);
     }
 }
Exemplo n.º 20
0
        public async Task write_csv_async_writes_only_requested_properties_if_specified()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                var items = new TestType1[]
                {
                    new TestType1
                    {
                        Property1 = "1",
                        Property2 = "2",
                        Property3 = "3"
                    },
                    new TestType1
                    {
                        Property1 = "4",
                        Property2 = "5",
                        Property3 = "6"
                    }
                };

                await items.WriteCsvAsync(writer, true, new string[] { "Property2" });
                Assert.Equal("Property2<EOL>2<EOL>5<EOL>", stringWriter.ToString());
            }
        }
Exemplo n.º 21
0
 public async Task write_csv_async_throws_if_csv_writer_is_disposed()
 {
     var writer = new CsvWriter(new StringWriter());
     writer.Dispose();
     await Assert.ThrowsAsync<ObjectDisposedException>(() => new DateTime[0].WriteCsvAsync(writer));
 }
Exemplo n.º 22
0
 public async Task write_csv_async_throws_if_object_to_string_converter_is_null()
 {
     var writer = new CsvWriter(new StringWriter());
     await Assert.ThrowsAsync<ArgumentNullException>(() => new List<DateTime>().WriteCsvAsync(writer, true, new string[] { "Date" }, null));
 }
            public async Task ExportAsync(CancellationToken cancellationToken, Action<int> reportProgress)
            {
                reportProgress = reportProgress ?? delegate { };
                var context = SynchronizationContext.Current;

                using (stream)
                using (var writer = new CsvWriter(stream))
                {
                    var extractor = new DocumentColumnsExtractor(columns);
                    writer.WriteHeaderRecord(columns.Select(c => c.Header));

                    // we do the streaming of documents on a background thread mainly to escape the
                    // SynchronizationContext: when there's no synchronization context involved the
                    // async methods can resume on any thread instead of having to hop back to the UI thread.
                    // This avoids massive overheads
                    await TaskEx.Run(async () =>
                    {
                       var totalResults = new Reference<long>();

                        using (var documentsStream = await collectionSource.StreamAsync(totalResults))
                        {
                            IList<JsonDocument> documentBatch;
                            var fetchedDocuments = 0;

                            do
                            {
                                documentBatch = await GetNextBatch(documentsStream, cancellationToken);

                                fetchedDocuments += documentBatch.Count;

                                // extracting properties from the documents has to be done on the UI thread
                                // because it might involve using FrameworkElements and Silverlight databinding
                                context.Send(delegate
                                {
                                    WriteColumnsForDocuments(writer, documentBatch, extractor);
                                    reportProgress((int) (((double) fetchedDocuments/totalResults.Value)*100));
                                }, null);

                            } while (documentBatch.Count > 0);
                        }

                    });
                }
            }
Exemplo n.º 24
0
        public async Task write_csv_async_writes_converts_null_property_values_to_empty_strings()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                var items = new TestType2[]
                {
                    new TestType2
                    {
                        Property1 = null,
                        Property2 = 2d,
                        Property3 = 3,
                        Property4 = 4m
                    },
                    new TestType2
                    {
                        Property1 = null,
                        Property2 = 6d,
                        Property3 = 7,
                        Property4 = null
                    }
                };

                await items.WriteCsvAsync(writer);
                Assert.Equal("Property1,Property2,Property3,Property4<EOL>,2,3,4<EOL>,6,7,<EOL>", stringWriter.ToString());
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Gets the RecurringServices CSV for a role.
        /// </summary>
        /// <param name="roleId">The role id.</param>
        public byte[] GetRecurringServicesCSVForRole(Guid roleId)
        {
            var memoryStream = new MemoryStream();

            var csvWriter = new CsvWriter(memoryStream);

            csvWriter.WriteHeaderRecord("Service Type", "Client", "Location", "Address Line 1", "Frequency",
                                        "Start Date", "End Date", "Repeat Every", "Repeat On");

            var recurringServices = RecurringServicesForServiceProviderOptimized(roleId).Include(rs => rs.Client).Include(rs => rs.Repeat).Include(rs => rs.ServiceTemplate);

            //Force Load LocationField's Location
            //TODO: Optimize by IQueryable
            recurringServices.SelectMany(rs => rs.ServiceTemplate.Fields).OfType<LocationField>().Select(lf => lf.Value).ToArray();

            //join RecurringServices with client names
            var records = from rs in recurringServices
                          orderby rs.Client.Name
                          select new
                          {
                              RecurringService = rs,
                              ServiceType = rs.ServiceTemplate.Name,
                              ClientName = rs.Client.Name
                          };

            foreach (var record in records.ToArray())
            {
                //Get destination information from LocationField
                var destination = record.RecurringService.ServiceTemplate.GetDestination();
                var locationName = "";
                var address = "";
                if (destination != null)
                {
                    locationName = destination.Name;
                    address = destination.AddressLineOne;
                }

                var repeat = record.RecurringService.Repeat;

                //Select proper end date info
                var endDate = "";
                if (repeat.EndDate.HasValue)
                    endDate = repeat.EndDate.Value.ToShortDateString();
                else if (repeat.EndAfterTimes.HasValue)
                    endDate = repeat.EndAfterTimes.Value.ToString();

                #region setup RepeatOn string

                var frequency = repeat.Frequency;
                var repeatOn = "";
                if (frequency == Frequency.Weekly)
                {
                    var weeklyFrequencyDetail = repeat.FrequencyDetailAsWeeklyFrequencyDetail;
                    //Build a weekly frequency string
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Sunday))
                        repeatOn += "Sun";
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Monday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Mon";
                    }
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Tuesday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Tues";
                    }
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Wednesday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Wed";
                    }
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Thursday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Thur";
                    }
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Friday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Fri";
                    }
                    if (weeklyFrequencyDetail.Any(fd => fd == DayOfWeek.Saturday))
                    {
                        if (repeatOn.ToCharArray().Any())
                            repeatOn += ",";
                        repeatOn += "Sat";
                    }
                }
                else if (frequency == Frequency.Monthly)
                {
                    var monthlyFrequencyDetail = repeat.FrequencyDetailAsMonthlyFrequencyDetail;
                    if (monthlyFrequencyDetail.HasValue)
                        repeatOn = monthlyFrequencyDetail.Value == MonthlyFrequencyDetail.OnDayInMonth ? "Date" : "Day";
                    else
                        repeatOn = "Date";
                }

                #endregion

                //Convert frequency detail to:  day or date
                //"Service Type", "Client", "Location", "Address", "Frequency"
                csvWriter.WriteDataRecord(record.ServiceType, record.ClientName, locationName, address, frequency.ToString(),
                    //"Start Date", "End Date", "Repeat Every", "Repeat On"
                   repeat.StartDate.ToShortDateString(), endDate, repeat.RepeatEveryTimes.ToString(), repeatOn);
            }

            csvWriter.Close();

            var csv = memoryStream.ToArray();
            memoryStream.Dispose();

            return csv;
        }
Exemplo n.º 26
0
 public void write_csv_throws_if_object_to_string_converter_is_null()
 {
     var writer = new CsvWriter(new StringWriter());
     Assert.Throws<ArgumentNullException>(() => new List<DateTime>().WriteCsv(writer, true, new string[] { "Date" }, null));
 }
Exemplo n.º 27
0
        /// <summary>
        /// Converts the DataTable to a CSV.
        /// </summary>
        /// <param name="alternateHeaders">The alternate headers.</param>
        /// <param name="columnsIndexesToIgnore">The columns indexes to ignore.</param>
        /// <returns>A byte[] CSV.</returns>
        public byte[] ToCSV(IEnumerable<string> alternateHeaders = null, IEnumerable<int> columnsIndexesToIgnore = null)
        {
            var memoryStream = new MemoryStream();
            var csvWriter = new CsvWriter(memoryStream);

            var columnsToTake = this.Columns.Select(c => c.ColumnName).ToList();

            //Remove any column indexes to ignores
            if (columnsIndexesToIgnore != null)
                foreach (var columnIndexToIgnore in columnsIndexesToIgnore.OrderByDescending(ci => ci))
                    columnsToTake.RemoveAt(columnIndexToIgnore);

            //If alternateHeaders is not null use them for the header record
            //Otherwise use the datatable's column names for the header record
            csvWriter.WriteHeaderRecord(alternateHeaders.ToArray() ?? columnsToTake.ToArray());

            foreach (var row in this.Rows)
            {
                var rowValues = columnsToTake.Select(column => row[column]).ToArray();
                csvWriter.WriteDataRecord(rowValues);
            }

            csvWriter.Close();
            var csv = memoryStream.ToArray();
            memoryStream.Dispose();

            return csv;
        }
Exemplo n.º 28
0
        public async Task write_csv_async_uses_object_to_string_converter_if_specified()
        {
            using (var stringWriter = new StringWriter())
            using (var writer = new CsvWriter(stringWriter))
            {
                writer.NewLine = "<EOL>";

                var items = new TestType2[]
                {
                    new TestType2
                    {
                        Property1 = "1",
                        Property2 = 2d,
                        Property3 = 3,
                        Property4 = 4m
                    },
                    new TestType2
                    {
                        Property1 = "5",
                        Property2 = 6d,
                        Property3 = 7,
                        Property4 = 8m
                    }
                };

                await items.WriteCsvAsync(writer, true, new string[] { "Property1", "Property2" }, o => o.ToString() + "_SUFFIX");
                Assert.Equal("Property1,Property2<EOL>1_SUFFIX,2_SUFFIX<EOL>5_SUFFIX,6_SUFFIX<EOL>", stringWriter.ToString());
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets the locations CSV for a role.
        /// </summary>
        /// <param name="roleId">The role id.</param>
        /// <param name="clientId">The optional client id filter.</param>
        /// <param name="regionId">The optional region id filter.</param>
        /// <returns></returns>
        public byte[] GetLocationsCSVForRole(Guid roleId, Guid clientId, Guid regionId)
        {
            var businessAccount = ObjectContext.Owner(roleId).First();

            var memoryStream = new MemoryStream();

            var csvWriter = new CsvWriter(memoryStream);

            csvWriter.WriteHeaderRecord("Client", "Location", "Address 1", "Address 2", "City", "State", "Country Code", "Zip Code",
                                        "Region", "Latitude", "Longitude");

            var locations = ObjectContext.Locations.Where(loc => loc.BusinessAccountId == businessAccount.Id && !loc.BusinessAccountIdIfDepot.HasValue);

            //Add client context if it exists
            if (clientId != Guid.Empty)
                locations = locations.Where(loc => loc.ClientId == clientId);

            //Add region context if it exists
            if (regionId != Guid.Empty)
                locations = locations.Where(loc => loc.RegionId == regionId);

            var records = from loc in locations
                          //Get the Clients names
                          join c in ObjectContext.Clients
                              on loc.Client.Id equals c.Id
                          orderby loc.AddressLineOne
                          select new
                          {
                              ClientName = c.Name,
                              loc.Name,
                              loc.AddressLineOne,
                              loc.AddressLineTwo,
                              loc.AdminDistrictTwo,
                              loc.AdminDistrictOne,
                              loc.PostalCode,
                              loc.CountryCode,
                              RegionName = loc.Region.Name,
                              loc.Latitude,
                              loc.Longitude
                          };

            foreach (var record in records.ToArray())
                csvWriter.WriteDataRecord(record.ClientName, record.Name, record.AddressLineOne, record.AddressLineTwo, record.AdminDistrictTwo, record.AdminDistrictOne, record.PostalCode, record.CountryCode, record.RegionName,
                                       record.Latitude, record.Longitude);

            csvWriter.Close();

            var csv = memoryStream.ToArray();
            memoryStream.Dispose();

            return csv;
        }
Exemplo n.º 30
0
        public async Task write_csv_async_returns_number_of_items_written()
        {
            using (var writer = new CsvWriter(new StringWriter()))
            {
                writer.WriteRecord("some", "record");

                var items = new TestType1[]
                {
                    new TestType1
                    {
                        Property1 = "1",
                        Property2 = "2",
                        Property3 = "3"
                    },
                    new TestType1
                    {
                        Property1 = "4",
                        Property2 = "5",
                        Property3 = "6"
                    }
                };

                Assert.Equal(2, await items.WriteCsvAsync(writer));
                Assert.Equal(2, await items.WriteCsvAsync(writer, false));
            }
        }