public async Task AttrsExport_Test() { IExporter exporter = new CsvExporter(); var filePath = GetTestFilePath($"{nameof(AttrsExport_Test)}.csv"); DeleteFile(filePath); var data = GenFu.GenFu.ListOf <ExportTestDataWithAttrs>(100); foreach (var item in data) { item.LongNo = 45875266524; } var result = await exporter.Export(filePath, data); result.ShouldNotBeNull(); File.Exists(filePath).ShouldBeTrue(); using (var reader = new StreamReader(filePath)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <AutoMap <ExportTestDataWithAttrs> >(); var exportDatas = csv.GetRecords <ExportTestDataWithAttrs>().ToList(); exportDatas.Count().ShouldBe(100); var exportData = exportDatas.FirstOrDefault(); exportData.Time1.ToString().ShouldBeGreaterThanOrEqualTo(exportData.Time1.ToString("yyyy-MM-dd")); exportData.Time2.ToString() .ShouldBeGreaterThanOrEqualTo(exportData.Time2?.ToString("yyyy-MM-dd HH:mm:ss")); } }
public void GetNumberWithoutNumber() { String street = "C/O ADAC branch"; Assert.AreEqual(String.Empty, CsvExporter.IntrashipGetStreetNumber(street)); Assert.AreEqual("C/O ADAC branch", CsvExporter.IntrashipGetStreetNameOnly(street)); }
public async Task ExportHeaderAsByteArray_Test() { IExporter exporter = new CsvExporter(); var filePath = GetTestFilePath($"{nameof(ExportHeaderAsByteArray_Test)}.csv"); DeleteFile(filePath); var result = await exporter.ExportHeaderAsByteArray(GenFu.GenFu.New <ExportTestDataWithAttrs>()); result.ShouldNotBeNull(); result.Length.ShouldBeGreaterThan(0); result.ToCsvExportFileInfo(filePath); File.Exists(filePath).ShouldBeTrue(); //using (var reader = new StreamReader(filePath)) //using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) //{ // csv.Configuration.RegisterClassMap<AutoMap<ExportTestDataWithAttrs>>(); // var datas = csv.GetRecords<ExportTestDataWithAttrs>().ToList(); // // datas.Count.ShouldBe(100); //} //using (var pck = new ExcelPackage(new FileInfo(filePath))) //{ // //检查转换结果 // var sheet = pck.Workbook.Worksheets.First(); // sheet.Name.ShouldBe("测试"); // sheet.Dimension.Columns.ShouldBe(9); //} }
public void GetNumberWithWhitespaceAndDot() { String street = "My Str.6"; Assert.AreEqual("6", CsvExporter.IntrashipGetStreetNumber(street)); Assert.AreEqual("My Str.", CsvExporter.IntrashipGetStreetNameOnly(street)); }
public void GetNumberWithoutWhitespace() { String street = "Teststr.4"; Assert.AreEqual("4", CsvExporter.IntrashipGetStreetNumber(street)); Assert.AreEqual("Teststr.", CsvExporter.IntrashipGetStreetNameOnly(street)); }
public void GetNumberWithColon() { String street = "corso vittorio emanuele,10"; Assert.AreEqual("10", CsvExporter.IntrashipGetStreetNumber(street)); Assert.AreEqual("corso vittorio emanuele", CsvExporter.IntrashipGetStreetNameOnly(street)); }
static void Main(string[] args) { var commandLineParser = new CommandLineParser(); var options = commandLineParser.Parse(args); var inputReader = new InputReader(); string result = null; if (options.Type == "-u") { result = inputReader.FromUrlAsync(options.Source).Result; } else if (options.Type == "-f") { result = inputReader.FromFileAsync(options.Source).Result; } else { throw new NotImplementedException("The source type isn't valid. Use -u option to urls or -f for files."); } JObject data = JObject.Parse(result); var dataCollector = new DataCollector(); var output = dataCollector.Query(data, options.RootElement, options.Fields); var exporter = new CsvExporter(); exporter.Export(output); }
public void TestExport() { m_FileSystem = new DynamicMock(typeof(IFileSystem)); List <Context> selected = new List <Context>(); Context result = new Context(); result.Tokens.Add("a"); result.Tokens.Add("b"); result.Tokens.Add("c"); Context branch = result.Branch("b1"); branch.Tokens.Add("d"); selected.Add(result); IExporter exporter = new CsvExporter(); m_FileSystem.Expect("WriteAllText", @"c:\abc.csv", string.Format(".Word.;b1{0}abc;abcd{0}", Environment.NewLine)); exporter.Export(selected, @"c:\abc.csv", (IFileSystem)m_FileSystem.MockInstance); m_FileSystem.Verify(); }
private void Export_Click(object sender, RoutedEventArgs e) { const string path = "test.csv"; IExporter csvExporter = new CsvExporter(';'); dataGrid.ExportUsingRefection(csvExporter, path); }
public async ValueTask <IActionResult> Csv([FromServices] CsvExporter csvExporter) { return(await csvExporter.MakeFileResult( "sample.csv", typeof(ExampleViewCsvMap), QueryExampleEnumerable())); }
public static void Register(string settingsFile, string costDataFile, string exportFile = "", EnExportType exportType = EnExportType.Console, IHtmlWrapper wrapper = null) { IMlogger mLogger = new Mlogger(); IAppConfiguration appConfig = new ApplicationConfiguration(settingsFile, costDataFile); TinyIoCContainer.Current.Register <IMlogger>(mLogger); TinyIoCContainer.Current.Register <IAppConfiguration>(appConfig); IDataExporter exporter = null; switch (exportType) { case EnExportType.Console: exporter = new ConsoleWriter(); break; case EnExportType.Csv: exporter = new CsvExporter(mLogger, exportFile); break; case EnExportType.Html: if (wrapper != null) { exporter = new HtmlExporter(mLogger, exportFile, wrapper); } else { // Fall back to Consolewriter - ideally we should log this failure... exporter = new ConsoleWriter(); } break; } TinyIoCContainer.Current.Register <IDataExporter>(exporter); }
public static void Main(string[] args) { Console.WriteLine("Initiating benchmarking"); var config = ManualConfig .Create(DefaultConfig.Instance); // ensure numbers in csv do not have units var csvExporter = new CsvExporter( CsvSeparator.CurrentCulture, new SummaryStyle() { PrintUnitsInHeader = true, PrintUnitsInContent = false, TimeUnit = BenchmarkDotNet.Horology.TimeUnit.Millisecond, }); config.Add(csvExporter); // I experimented with removing outliers but I think other processes on the system create outliers more // than abnormal data access patterns config.Add( Job.Default.WithRemoveOutliers(true)); var switcher = new BenchmarkSwitcher(new[] { typeof(GetFileBenchmark), typeof(FileExistsBenchmark) }); var summary = switcher.Run(args, config); Console.WriteLine("Benchmarking complete"); }
private void CreateProjects() { Log.Info(""); Log.Info("Creating projects..."); List <BimProject> _projectsToCreate = DataController.GetBimProjects(); if (_projectsToCreate == null || _projectsToCreate.Count < 1) { Log.Info("Project creation was unable to start due to insufficient input data"); return; } for (int i = 0; i < DataController._projectTable.Rows.Count; i++) { string name = Convert.ToString(DataController._projectTable.Rows[i]["name"]); Log.Info($"- processing row {i + 1} - project name: {name}"); BimProject project = _projectsToCreate.FirstOrDefault(p => p.name != null && p.name.Equals(name)); if (project == null || false == CheckRequiredParams(project, DataController._projectTable.Rows[i])) { Log.Error($"There's an incomplete input data"); DataController._projectTable.Rows[i]["result"] = ResultCodes.IncompleteInputData; continue; } DataController.AddProject(project, null, i); } CsvExporter.WriteResults(DataController._projectTable, _options, _options.FilePath); }
public Config() { AddJob(Job.ShortRun .WithLaunchCount(1) .WithToolchain(new InProcessEmitToolchain(TimeSpan.FromHours(1), true)) .WithId("InProcess") ); var artifactsPath = Environment.GetEnvironmentVariable("BENCHMARK_OUTPUT_PATH"); if (!string.IsNullOrEmpty(artifactsPath)) { WithArtifactsPath(artifactsPath); } WithOption(ConfigOptions.DisableOptimizationsValidator, true); WithOption(ConfigOptions.JoinSummary, true); AddLogger(DefaultConfig.Instance.GetLoggers().ToArray()); // manual config has no loggers by default AddExporter(DefaultConfig.Instance.GetExporters().Where(v => !(v is CsvExporter)).ToArray()); // manual config has no exporters by default var csv = new CsvExporter( CsvSeparator.Semicolon, new SummaryStyle(CultureInfo.CurrentCulture, true, SizeUnit.B, TimeUnit.Nanosecond, false, true) ); AddExporter(csv); AddExporter(JsonExporter.Full); AddColumnProvider(DefaultConfig.Instance.GetColumnProviders().ToArray()); // manual config has no columns by default }
static async Task Main(string[] args) { using (var db = new skistore_seContext()) { var shops = await db.PsShop.Where(x => x.Name == "Mtbstore").ToListAsync(); foreach (var shop in shops) { var langs = await db.PsLang.ToListAsync(); foreach (var lang in langs) { var imageNames = new List <string>(); var exports = new List <ExportModel>(); Console.WriteLine($"Starting export for {lang.IsoCode} on {shop.Name}"); await ExportProductsFromCategory(db, shop.IdCategory, new List <string>(), shop.IdShop, lang, exports, imageNames); var fileName = $"export-{shop.Name}-{lang.IsoCode}.csv"; await CsvExporter.Export(File.OpenWrite(fileName), exports, new ExportOptions { WriteSep = false }); GenerateImageDownloadFilelist(shop, imageNames); Console.WriteLine($"Exported {exports.Count} products"); } } } Console.WriteLine("Finished! Press any key to exit"); Console.ReadKey(); }
public void ExportTabularCsvWithoutSeparator() { Worksheet ws = Instance.Default.ActiveWorkbook.Worksheets.Add(); ws.Cells[3, 5] = "hello"; ws.Cells[3, 6] = "13"; // For testing we 'hide' a pipe symbol in the field. ws.Cells[4, 5] = "wor|d"; ws.Cells[4, 6] = 88.5; CsvExporter model = new CsvExporter(); string fn = System.IO.Path.GetTempFileName(); model.FileName = fn; model.FieldSeparator = " "; model.Tabularize = true; // Use a funky decimal separator model.DecimalSeparator = "~"; model.Execute(); string contents = System.IO.File.ReadAllText(fn); string expected = String.Format( "hello 13 {0}wor|d 88~5{0}", Environment.NewLine); Assert.AreEqual(expected, contents); System.IO.File.Delete(fn); }
public void TestExport() { IList <LineItem> items = new List <LineItem>(); items.Add(new LineItem("__--Tag--__") { Items = { new TableValueItem { Column = 5, Value = "Test" } } }); items.Add(new LineItem("__--Tag--__") { Items = { new TableValueItem { Column = 6, Value = "Test2" }, new TableValueItem { Column = 8, Value = "17" } } }); CsvExporter exporter = new CsvExporter(); exporter.Export(ExportFile, items); }
static void Main(string[] args) { // set our default folder and query names string folderName = null; string queryName = null; string exportFormat = null; // use the arguments from the command line if we got any if (args.Length == 3) { folderName = args[0]; queryName = args[1]; exportFormat = args[2]; } else { throw new ArgumentException("Command line arguments not provided"); } // give our bitly client our access token if there is one (not required) BitlyClient.AccessToken = ConfigurationManager.AppSettings["BitlyAccessToken"]; // grab our team services info var token = ConfigurationManager.AppSettings["TeamServicesPersonalAccessToken"]; var url = ConfigurationManager.AppSettings["TeamServicesCollectionUrl"]; var project = ConfigurationManager.AppSettings["TeamServicesProjectName"]; // make sure we have the necessary info if (string.IsNullOrEmpty(token) == true || string.IsNullOrEmpty(url) == true || string.IsNullOrEmpty(project) == true) { Console.WriteLine("You must set the Team Services Personal Access Token, Colection URL, and project name in the App.config"); return; } // create our team services client var client = new TeamServicesClient(url, token, project); // retrieve the result set for the given query var result = client.RunQuery(folderName, queryName); // shorten the urls in the items BitlyClient.ShortenUrls(result.Items); // export the query results switch (exportFormat) { case "csv": CsvExporter.ExportItems(queryName, result); break; case "html": HtmlExporter.ExportItems(queryName, result); break; } }
public void Save_UsingDefaultSettingsButMappingsSomeDataInvalid_ResultIsAsExpected() { String expected = "\uFEFFLabel,Enabled,Number,Currency\r\n" + "Void,Nope,100,\"1,234\"\r\n" + "Label-2,Yeah,100,\"2,345\"\r\n" + "Void,Nope,100,\"3,456\"\r\n" + "Label-4,Yeah,100,\"4,567\"\r\n" + "Void,Nope,100,\"5,678\"\r\n" + "Label-6,Yeah,100,\"6,789\"\r\n"; MemoryStream stream = new MemoryStream(); CsvSettings settings = new CsvSettings() { Mappings = new CsvMappings() { TrueValue = "Yeah", FalseValue = "Nope", NullValue = "Void" }, }; List <TestClass1> values = new List <TestClass1>() { new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 1.234m, }, new TestClass1() { Label = "Label-2", Enabled = true, Number = 100, Currency = 2.345m, }, new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 3.456m, }, new TestClass1() { Label = "Label-4", Enabled = true, Number = 100, Currency = 4.567m, }, new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 5.678m, }, new TestClass1() { Label = "Label-6", Enabled = true, Number = 100, Currency = 6.789m, }, }; CsvExporter <TestClass1> .Save(values, stream, settings); String actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.That(actual, Is.EqualTo(expected)); }
private void ConfigureStateMachine() { // Use builder pattern to configure each state _stateMachine.ConfigureState(SaleState.Open) // Add possible transitions .AddTransition(SaleEvent.Cancel, SaleState.Cancelled, condition: sale => sale.IsCancellable()) .AddTransition(SaleEvent.SetItemQuantity, SaleState.Overpaid, condition: sale => sale.HasPositiveBalance()) .AddTransition(SaleEvent.SetItemQuantity, SaleState.Paid, condition: sale => sale.IsPaid) .AddTransition(SaleEvent.Pay, SaleState.Overpaid, condition: sale => sale.HasPositiveBalance()) .AddTransition(SaleEvent.Pay, SaleState.Paid, condition: sale => sale.IsPaid) // Add trigger actions -- how to process requests passed from Sale // - Include parameter type where required .AddTriggerAction <SaleItem>(SaleEvent.AddItem, (sale, item) => sale.AddItemInternal(item)) .AddTriggerAction <SaleItem>(SaleEvent.SetItemQuantity, (sale, item) => sale.SetItemQuantityInternal(item)) .AddTriggerAction <SaleItem>(SaleEvent.DeleteItem, (sale, item) => sale.DeleteItemInternal(item)) .AddTriggerAction <Payment>(SaleEvent.Pay, (sale, payment) => sale.AddPaymentInternal(payment)) .AddTriggerAction <Change>(SaleEvent.GiveChange, (sale, change) => sale.AddChangeInternal(change)) .AddTriggerAction(SaleEvent.Cancel, sale => sale.CancelInternal()); _stateMachine.ConfigureState(SaleState.Overpaid) .MakeSubstateOf(_stateMachine.ConfigureState(SaleState.Open)) // This inherits all of Open's configuration unless overridden // Overpaid can go back to Open if the balance goes negative .AddTransition(SaleEvent.GiveChange, SaleState.Open, condition: sale => sale.HasNegativeBalance()) .AddTransition(SaleEvent.AddItem, SaleState.Open, condition: sale => sale.HasNegativeBalance()) .AddTransition(SaleEvent.SetItemQuantity, SaleState.Open, condition: sale => sale.HasNegativeBalance()) // Can't add payments when customer over paid .AddTriggerAction <Payment>(SaleEvent.Pay, (sale, payment) => throw new InvalidOperationException("Cannot pay on an overpaid sale")); _stateMachine.ConfigureState(SaleState.Finalized) // This is the parent class for any finalized state -- Paid and Cancelled // -- No actions or transitions allowed .AddTriggerAction <SaleItem>(SaleEvent.AddItem, (_, item) => throw new InvalidOperationException("Cannot add item to a finalized sale")) .AddTriggerAction <SaleItem>(SaleEvent.SetItemQuantity, (_, item) => throw new InvalidOperationException("Cannot change item quantities a finalized sale")) .AddTriggerAction <SaleItem>(SaleEvent.DeleteItem, (_, item) => throw new InvalidOperationException("Cannot delete item on a finalized sale")) .AddTriggerAction <Payment>(SaleEvent.Pay, (_, payment) => throw new InvalidOperationException("Cannot pay on a finalized sale")) .AddTriggerAction <Change>(SaleEvent.GiveChange, (_, change) => throw new InvalidOperationException("Cannot give change on a finalized sale")) .AddTriggerAction(SaleEvent.Cancel, sale => throw new InvalidOperationException("Cannot cancel a finalized sale")); _stateMachine.ConfigureState(SaleState.Paid) .MakeSubstateOf(_stateMachine.ConfigureState(SaleState.Finalized)); _stateMachine.ConfigureState(SaleState.Cancelled) .MakeSubstateOf(_stateMachine.ConfigureState(SaleState.Finalized)); #if DEBUG // This is how to export state configuration to Csv and/or DotGraph var configSummary = _stateMachine.GetSummary(); Debug.WriteLine(CsvExporter <SaleState, SaleEvent> .Export(configSummary)); Debug.WriteLine(DotGraphExporter <SaleState, SaleEvent> .Export(configSummary)); // Plug the output of the DotGraphExporter into https://dreampuf.github.io/GraphvizOnline to see graph of current configuration #endif }
public async Task ExportTestDataWithoutExcelExporter_Test() { IExporter exporter = new CsvExporter(); var filePath = GetTestFilePath($"{nameof(ExportTestDataWithoutExcelExporter_Test)}.csv"); DeleteFile(filePath); var result = await exporter.Export(filePath, GenFu.GenFu.ListOf <ExportTestDataWithoutExcelExporter>()); result.ShouldNotBeNull(); File.Exists(filePath).ShouldBeTrue(); }
public async Task ExportAsByteArray_Test() { IExporter exporter = new CsvExporter(); var filePath = GetTestFilePath($"{nameof(ExportAsByteArray_Test)}.csv"); DeleteFile(filePath); var result = await exporter.ExportAsByteArray(GenFu.GenFu.ListOf <ExportTestData>()); result.ShouldNotBeNull(); result.Length.ShouldBeGreaterThan(0); File.WriteAllBytes(filePath, result); File.Exists(filePath).ShouldBeTrue(); }
private static async Task SearchForObjectsAroundRaDecAsync(ReceivedMessage receivedMessage, Match regexMatch, SimbadClient simbadClient) { RaDecCoordinate centerCoordinates = null; const float radiusInDegrees = 0.5f; try { if (regexMatch.Groups["CenterOfSearchRA"].Success) { centerCoordinates = new RaDecCoordinate( double.Parse(regexMatch.Groups["CenterOfSearchRA"].Value, CultureInfo.InvariantCulture), double.Parse(regexMatch.Groups["CenterOfSearchDEC"].Value, CultureInfo.InvariantCulture)); } else if (regexMatch.Groups["CenterOfSearchName"].Success) { var name = regexMatch.Groups["CenterOfSearchName"].Value; var queryAroundObject = simbadClient.FindObjectByName(name); if (queryAroundObject == null) { await receivedMessage.Channel.SendMessageAsync($"No object with name {name} found in the SIMBAD databse!").ConfigureAwait(false); return; } centerCoordinates = queryAroundObject.RaDecCoordinate; } } finally { if (centerCoordinates == null) { await receivedMessage.Channel.SendMessageAsync("Could not parse RA/DEC coordinates").ConfigureAwait(false); } } var objectsAroundTarget = simbadClient.QueryAround(centerCoordinates, radiusInDegrees); var csvString = CsvExporter.AstronomicalObjectsToCsv(objectsAroundTarget); await receivedMessage.Channel.SendMessageAsync($"Found {objectsAroundTarget.Count} objects around {centerCoordinates} within a radius of {radiusInDegrees}°:").ConfigureAwait(false); await receivedMessage.Channel.SendMessageAsync( new SendMessage( content : null, new List <Attachment> { new SendAttachment { Name = "queryResult.csv", Content = Encoding.ASCII.GetBytes(csvString) } })).ConfigureAwait(false); }
public FileDownloadable ExportTransactionsToCsv(ListRequest request) { var result = Repository.List(request); var name = $"Export for {DateTimeContext.Today.ToString("yyyy.MM.dd")}.csv"; var items = Mapper.Map <List <TransactionsExportToCsvModel> >(result.Data); var exporter = new CsvExporter { Delimiter = ";" }; return(new FileDownloadable(name, "text/csv", exporter.Export(items))); }
public void Save_UsingUtf32EnglishCommaAllDataValid_ResultIsAsExpected() { String expected = "\uFEFFLabel,Enabled,Number,Currency\r\n" + "Label-1,false,100,1.234\r\n" + "Label-2,true,100,2.345\r\n" + "Label-3,false,100,3.456\r\n" + "Label-4,true,100,4.567\r\n" + "Label-5,false,100,5.678\r\n" + "Label-6,true,100,6.789\r\n"; MemoryStream stream = new MemoryStream(); CsvSettings settings = new CsvSettings() { Encoding = Encoding.UTF32, Heading = true, Separator = ',', Culture = CultureInfo.GetCultureInfo("en-US"), }; List <TestClass1> values = new List <TestClass1>() { new TestClass1() { Label = "Label-1", Enabled = false, Number = 100, Currency = 1.234m, }, new TestClass1() { Label = "Label-2", Enabled = true, Number = 100, Currency = 2.345m, }, new TestClass1() { Label = "Label-3", Enabled = false, Number = 100, Currency = 3.456m, }, new TestClass1() { Label = "Label-4", Enabled = true, Number = 100, Currency = 4.567m, }, new TestClass1() { Label = "Label-5", Enabled = false, Number = 100, Currency = 5.678m, }, new TestClass1() { Label = "Label-6", Enabled = true, Number = 100, Currency = 6.789m, }, }; CsvExporter <TestClass1> .Save(values, stream, settings); String actual = Encoding.UTF32.GetString(stream.ToArray()); Assert.That(actual, Is.EqualTo(expected)); }
public void Save_UsingAsciiForDoubleQuoteEscaping_ResultIsAsExpected() { String expected = "Label,Text\r\n" + "\"Label \"\"1\"\"\",\"\"\"Double Quotes\"\" included\"\r\n" + "\"Label \"\"2\"\"\",Double Quotes not included\r\n" + "\"Label \"\"3\"\"\",\"\"\"Double\"\" Quotes included\"\r\n" + "\"Label \"\"4\"\"\",Double Quotes not included\r\n" + "\"Label \"\"5\"\"\",\"Double \"\"Quotes\"\" included\"\r\n" + "\"Label \"\"6\"\"\",Double Quotes not included\r\n"; MemoryStream stream = new MemoryStream(); CsvSettings settings = new CsvSettings() { Encoding = Encoding.ASCII }; List <TestClass2> values = new List <TestClass2>() { new TestClass2() { Label = "Label \"1\"", Text = "\"Double Quotes\" included" }, new TestClass2() { Label = "Label \"2\"", Text = "Double Quotes not included" }, new TestClass2() { Label = "Label \"3\"", Text = "\"Double\" Quotes included" }, new TestClass2() { Label = "Label \"4\"", Text = "Double Quotes not included" }, new TestClass2() { Label = "Label \"5\"", Text = "Double \"Quotes\" included" }, new TestClass2() { Label = "Label \"6\"", Text = "Double Quotes not included" }, }; CsvExporter <TestClass2> .Save(values, stream, settings); String actual = Encoding.UTF8.GetString(stream.ToArray()); Assert.That(actual, Is.EqualTo(expected)); }
public void Save_UsingAsciiGermanHashSomeDataInvalid_ResultIsAsExpected() { String expected = "Label#Enabled#Number#Currency\r\n" + "#false#100#1,234\r\n" + "Label-2#true#100#2,345\r\n" + "#false#100#3,456\r\n" + "Label-4#true#100#4,567\r\n" + "#false#100#5,678\r\n" + "Label-6#true#100#6,789\r\n"; MemoryStream stream = new MemoryStream(); CsvSettings settings = new CsvSettings() { Encoding = Encoding.ASCII, Heading = true, Separator = '#', Culture = CultureInfo.GetCultureInfo("de-DE"), }; List <TestClass1> values = new List <TestClass1>() { new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 1.234m, }, new TestClass1() { Label = "Label-2", Enabled = true, Number = 100, Currency = 2.345m, }, new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 3.456m, }, new TestClass1() { Label = "Label-4", Enabled = true, Number = 100, Currency = 4.567m, }, new TestClass1() { Label = null, Enabled = false, Number = 100, Currency = 5.678m, }, new TestClass1() { Label = "Label-6", Enabled = true, Number = 100, Currency = 6.789m, }, }; CsvExporter <TestClass1> .Save(values, stream, settings); String actual = Encoding.ASCII.GetString(stream.ToArray()); Assert.That(actual, Is.EqualTo(expected)); }
protected void DownloadDpdButton_Click(Object sender, EventArgs e) { Byte[] buffer = CsvExporter.CreateDPD(); this.Response.Clear(); if (buffer != null) { this.Response.ContentType = "application/vnd.ms-excel"; this.Response.AddHeader("content-disposition", "attachment; filename=DpdLieferungen.csv"); this.Response.OutputStream.Write(buffer, 0, buffer.Length); } this.Response.End(); }
public void Should_read_data() { var resultRows = Resolve<GetOldDbAsResultRows>().Run(); var resultRowsAggregated = Resolve<GetOldDbAsAggregatedRows>().Run(); var resultOrganisations = Resolve<GetOldDbAsModel>().Run(); Console.WriteLine(resultRows.Count); Console.WriteLine(resultRowsAggregated.Count); Console.WriteLine(resultOrganisations.Organisations.Count); var csvExporter = new CsvExporter(); csvExporter.Run(resultOrganisations.Organisations, "unternehmen.csv"); Resolve<Importer>().Run(); }
private static void RunOptionsAndReturnExitCode(Options options) { try { LogfileExtractor.Service.LogFileExtractor logFileExtractor = new LogfileExtractor.Service.LogFileExtractor(options.LogFile); IList <LineItem> items = logFileExtractor.Extract(options.Tag); CsvExporter exporter = new CsvExporter(); exporter.Export(options.Output, items); } catch (Exception ex) { Console.WriteLine("Failed to extract logfile" + ex); } }
public async Task ExportHeaderAsByteArray_Test() { IExporter exporter = new CsvExporter(); var filePath = GetTestFilePath($"{nameof(ExportHeaderAsByteArray_Test)}.csv"); DeleteFile(filePath); var result = await exporter.ExportHeaderAsByteArray(GenFu.GenFu.New <ExportTestDataWithAttrs>()); result.ShouldNotBeNull(); result.Length.ShouldBeGreaterThan(0); result.ToCsvExportFileInfo(filePath); File.Exists(filePath).ShouldBeTrue(); }
public void TestExport() { m_FileSystem = new DynamicMock(typeof(IFileSystem)); List<Context> selected = new List<Context>(); Context result = new Context(); result.Tokens.Add("a"); result.Tokens.Add("b"); result.Tokens.Add("c"); Context branch = result.Branch("b1"); branch.Tokens.Add("d"); selected.Add(result); IExporter exporter = new CsvExporter(); m_FileSystem.Expect("WriteAllText", @"c:\abc.csv", string.Format(".Word.;b1{0}abc;abcd{0}", Environment.NewLine)); exporter.Export(selected, @"c:\abc.csv", (IFileSystem)m_FileSystem.MockInstance); m_FileSystem.Verify(); }
private void ExportToCsv() { //if (System.Windows.Interop.BrowserInteropHelper.IsBrowserHosted) //{ //MessageBox.Show("Due to restricted user-access permissions, this feature cannot be demonstrated when the Live Explorer is running as an XBAP browser application. Please download the full Xceed DataGrid for WPF package and run the Live Explorer as a desktop application to try out this feature.", "Feature unavailable"); //return; //} // The simplest way to export in CSV format is to call the // DataGridControl.ExportToCsv() method. However, if you want to specify export // settings, you have to take the longer, more descriptive and flexible route: // the CsvExporter class. CsvExporter csvExporter = new CsvExporter(this.GridDetails); // By setting the Culture to the CurrentCulture (system culture by default), the // date and number formats set in the regional settings will be used. csvExporter.FormatSettings.Culture = CultureInfo.CurrentCulture; csvExporter.FormatSettings.DateTimeFormat = (string)this.dateTimeFormatComboBox.SelectedValue; csvExporter.FormatSettings.NumericFormat = (string)this.numberFormatComboBox.SelectedValue; csvExporter.FormatSettings.Separator = (char)this.separatorComboBox.SelectedValue; csvExporter.FormatSettings.TextQualifier = (char)this.textQualifierComboBox.SelectedValue; csvExporter.IncludeColumnHeaders = this.includeColumnHeadersCheckBox.IsChecked.GetValueOrDefault(); csvExporter.RepeatParentData = this.repeatParentDataCheckBox.IsChecked.GetValueOrDefault(); csvExporter.DetailDepth = Convert.ToInt32(this.detailDepthTextBox.Value); csvExporter.UseFieldNamesInHeader = this.UseFieldNamesInHeaderCheckBox.IsChecked.GetValueOrDefault(); Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog(); saveFileDialog.Filter = "CSV file (*.csv)|*.csv|Text file (*.txt)|*.txt|All files (*.*)|*.*"; try { if (saveFileDialog.ShowDialog().GetValueOrDefault()) { using (Stream stream = saveFileDialog.OpenFile()) { csvExporter.Export(stream); } } } catch { } }