static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (File.Exists("Ustawienia.csv")) { // Deserialization IList<Ustawienia> deserializedData = null; using (var stream = new FileStream("Ustawienia.csv", FileMode.Open, FileAccess.Read)) { var cs = new CsvSerializer<Ustawienia>() { UseTextQualifier = true, }; deserializedData = cs.Deserialize(stream); } Singleton.ustawienia = deserializedData.ElementAt(0); // Deserialization IList<Kombinacja> deserializedData3 = null; using (var stream = new FileStream("Kombinacje.csv", FileMode.Open, FileAccess.Read)) { var cs = new CsvSerializer<Kombinacja>() { UseTextQualifier = true, }; deserializedData3 = cs.Deserialize(stream); } Singleton.merged = (List<Kombinacja>)deserializedData3; if (File.Exists("Dane.csv")) { // Deserialization IList<Dane> deserializedData2 = null; using (var stream = new FileStream("Dane.csv", FileMode.Open, FileAccess.Read)) { var cs = new CsvSerializer<Dane>() { UseTextQualifier = true, }; deserializedData2 = cs.Deserialize(stream); } Singleton.dane = deserializedData2.ElementAt(0); Application.Run(new Eksperyment()); } else { Application.Run(new Powitanie()); } } else { Application.Run(new Panel()); } }
public static bool LoadCustomers() { string path = System.String.Format(@"{0}App_Data\us-500.csv", System.AppDomain.CurrentDomain.BaseDirectory); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { try { var cs = new CsvSerializer<Customer>() { UseTextQualifier = false, Separator = ',', RowSeparator = "\n", UseLineNumbers = false, ColumnsContainedInHeader = true }; Customers = cs.Deserialize(stream); _loaded = true; } catch { } } return _loaded; }
public void Can_serialize_Queue_Generic() { var queue = new Queue <ModelWithIdAndName>(); queue.Enqueue(ModelWithIdAndName.Create(1)); queue.Enqueue(ModelWithIdAndName.Create(2)); queue.Enqueue(ModelWithIdAndName.Create(3)); Serialize(queue); Assert.That(CsvSerializer.SerializeToString(queue), Is.EqualTo("Id,Name\r\n1,Name1\r\n2,Name2\r\n3,Name3\r\n")); }
public void Can_serialize_Stack_Generic() { var stack = new Stack <ModelWithIdAndName>(); stack.Push(ModelWithIdAndName.Create(1)); stack.Push(ModelWithIdAndName.Create(2)); stack.Push(ModelWithIdAndName.Create(3)); Serialize(stack); Assert.That(CsvSerializer.SerializeToString(stack), Is.EqualTo("Id,Name\r\n3,Name3\r\n2,Name2\r\n1,Name1\r\n")); }
public void SerializationTests(string filename) { using (var tempDirectory = new TempDirectory()) { var resourceFilename = Path.Join("Resources", filename + "-1.2.xml"); var inputBomString = File.ReadAllText(resourceFilename); var bom = Xml.Deserializer.Deserialize(inputBomString); var bomCsv = CsvSerializer.Serialize(bom); Snapshot.Match(bomCsv, SnapshotNameExtension.Create(filename)); } }
private ActionResult exportToCSV(List <WechatFollowReportView> wechatFollowReportList) { string[] headLine = { "StatisticsDate", "FollowCount", "UnFollowCount" }; CsvSerializer <WechatFollowReportView> csv = new CsvSerializer <WechatFollowReportView>(); csv.UseLineNumbers = false; string sRet = csv.Serialize(wechatFollowReportList, headLine); byte[] bits = System.Text.Encoding.UTF8.GetBytes(sRet); string fileName = "WeChatFollowReport_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".csv"; return(File(bits, "text/comma-separated-values", fileName)); }
public async Task SerializeAsyncTest() { var examples = CreateExamples(); var cs = new CsvSerializer <Example> { HasHeader = true }; var csv = await cs.SerializeAsync(examples); Assert.AreEqual(CreateExamplesCsv(), csv); }
static void InsertCSV_in_Itop() { TextReader reader = File.OpenText(_objectDataPath); List <ContactType> ListContactType = CsvSerializer.DeserializeFromReader <List <ContactType> >(reader); foreach (ContactType s in ListContactType) { // ContactType _ContactType = new ContactType(); Response QueryResult = new Response(); s.Create(s.name, out QueryResult); Console.WriteLine("{0} - add : {1}", className, s.name); } }
public void SerializeTest() { var examples = CreateExamples(); var cs = new CsvSerializer <Example> { HasHeader = true }; var csv = cs.Serialize(examples); Assert.AreEqual(CreateExamplesCsv(), csv); }
public void TestSepartorConflicting() { var Reader = StringToStreamReader("sep=,\nField1,Field2\n\"Hello\",\"World\""); var Options = new CsvDeserializationOptions { Separator = ';', UseTextQualifier = true }; var Result = CsvSerializer.Deserialize <HasFields>(Reader, Options); Assert.Single(Result); Assert.Equal("Hello", Result.First().Field1); Assert.Equal("World", Result.First().Field2); Assert.Equal(','.ToString(), Options.Separator.ToString()); }
public void QuoteChangeEscapeCharacterTest() { using (var writer = new StringWriter()) using (var csv = new CsvSerializer(writer)) { csv.Configuration.SanitizeForInjection = true; csv.Configuration.InjectionEscapeCharacter = '\''; csv.Write(new[] { "\"=one\"" }); writer.Flush(); Assert.AreEqual("\"'=one\"", writer.ToString()); } }
public static void WriteCsv(string outputFile, IEnumerable <Tuple <string, string> > valuesDictionary) { using (var writer = new StreamWriter(outputFile, false, Encoding.UTF8)) { var serializer = new CsvSerializer(writer); serializer.Configuration.Delimiter = Separator; serializer.Configuration.Encoding = Encoding.UTF8; serializer.Configuration.IgnoreBlankLines = true; serializer.Write(valuesDictionary.Select(x => x.Item1).ToArray()); //используется замена "переводов строк" , "табуляции" и "сдвига каретки" на "пробел" для сохранения формата csv файла serializer.Write(valuesDictionary.Select(x => Regex.Replace(x.Item2, "\n|\r|\t", " ")).ToArray()); } }
protected StopModel GetStopFromStopRef(OpenArchive gtfsArchive, string stopRef) { if (stopsList == null) { using (Stream stopsStream = gtfsArchive.zip.GetEntry("google_transit/stops.csv").Open()) { this.stopsList = CsvSerializer.DeserializeFromStream <List <StopModel> >(stopsStream); } } StopModel stopObj = stopsList.FirstOrDefault(o => o.stop_code == stopRef); return(stopObj); }
public async Task SerializeWriterAsyncTest() { var examples = CreateExamples(); var cs = new CsvSerializer <Example> { HasHeader = true }; var writer = new StringWriter(); await cs.SerializeAsync(writer, examples); Assert.AreEqual(CreateExamplesCsv(), writer.ToString()); }
protected RouteModel GetRouteFromRouteId(OpenArchive gtfsArchive, string routeId) { if (routeList == null) { using (Stream routeStream = gtfsArchive.zip.GetEntry("google_transit/routes.csv").Open()) { routeList = CsvSerializer.DeserializeFromStream <List <RouteModel> >(routeStream); } } RouteModel routeDetails = routeList.FirstOrDefault(o => o.route_id == routeId); return(routeDetails); }
protected TripModel GetTripFromTripId(OpenArchive gtfsArchive, int tripId) { if (tripList == null) { using (Stream tripStream = gtfsArchive.zip.GetEntry("google_transit/trips.csv").Open()) { tripList = CsvSerializer.DeserializeFromStream <List <TripModel> >(tripStream); } } TripModel tripDetails = tripList.FirstOrDefault(o => o.trip_id == tripId); return(tripDetails); }
public void TestDeserializeEnumerable() { var csvSerializer = new CsvSerializer(); var content = CreateContent(); var expected = CreateRecords(); var actual = csvSerializer.DeserializeEnumerable <Customer>(content); AssertUtilities.Equal(expected, actual); Assert.IsType <List <Customer> >(actual); }
public void TestIncompleteLine() { var Input = StringToStreamReader("Prop1,Prop2" + Environment.NewLine + "A" + Environment.NewLine + "C,D"); var Data = CsvSerializer.Deserialize <HasProperties>(Input); Assert.True(Data.Count() == 2); Assert.Equal("A", Data.First().Prop1); Assert.Null(Data.First().Prop2); Assert.Equal("C", Data.Last().Prop1); Assert.Equal("D", Data.Last().Prop2); }
private void btnSaveCSV_Click(object sender, EventArgs e) { // Serialization var data = GetPeople(); using (var stream = new FileStream("persons.csv", FileMode.Create, FileAccess.Write)) { var cs = new CsvSerializer <Person>() { UseTextQualifier = true, }; cs.Serialize(stream, data); } }
static void Main() { string path = "../../../example.csv"; var separator = ';'; var serializer = new CsvSerializer(separator); var movies = serializer.Read<Movie>(path); serializer.Write("../../../newFile.csv", movies); Console.Write("File created."); Console.ReadKey(); }
public async Task ProcessAsync(Uri uri, Stream outputStream) { using (var outputZip = new ZipArchive(outputStream, ZipArchiveMode.Create, leaveOpen: true)) using (var containerBuilder = new ContainerBuilder(outputZip)) { var stopWatch = new Stopwatch(); stopWatch.Start(); CSVMapping csvMapping = null; var streamParser = new StreamParser(); var file = _downloader.GetFile(uri); var zip = _zipProcessor.UnZip(file); foreach (var zipEntry in zip.Entries) { if (!zipEntry.FullName.ToLower().EndsWith(".xml")) { continue; } using (var inputStream = zipEntry.Open()) using (var stream = new MemoryStream()) { _transformer.Transform(inputStream, stream); if (stream.Length == 0) { continue; } stream.Position = 0; var data = await streamParser.Parse(stream); csvMapping = _mappingProvider.GetMappingByData(data); var serializer = new CsvSerializer(containerBuilder, csvMapping); await serializer.Serialize(data.ParsedEntities); } } // Add metadata to each archive if (csvMapping != null) { CSVMappingHelper.AddMetadata(outputZip, csvMapping); } stopWatch.Stop(); var ts = stopWatch.Elapsed; var elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); } }
private ActionResult ExportToCsv(List <ArticleInfoView> wechatFollowReportList) { string[] headLine = { "Id", "ArticleTitle", "APPName", "ArticleCateName", "ReadCount", "ThumbsUpCount", "PublishDate" }; var csv = new CsvSerializer <ArticleInfoView> { UseLineNumbers = false }; var sRet = csv.SerializeStream(wechatFollowReportList, headLine); var channelConfig = CommonService.GetAppList().FirstOrDefault(x => x.WeixinAppId.Equals(AppId.ToString(CultureInfo.InvariantCulture))); string fileHeadName = channelConfig == null?AppId.ToString(CultureInfo.InvariantCulture) : channelConfig.AppName; string fileName = fileHeadName + "_Article_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".csv"; return(File(sRet, "text/comma-separated-values", fileName)); }
internal override void LogWrite(LogParameters logInfo) { var serializer = new CsvSerializer <LogParameters>(); try { serializer.Serialize(logFilePath, logInfo); } catch (System.Exception) { Console.WriteLine($"DumbLogger. Error, log was not written into log file : {logFilePath}"); throw; } }
public static void WriteValues(CsvSerializer csv, Dictionary <string, object> data) { object[] valueObjs = new object[data.Values.Count]; data.Values.CopyTo(valueObjs, 0); string[] values = new string[valueObjs.Length]; for (int i = 0; i < valueObjs.Length; i++) { values[i] = ToEscapedString(valueObjs[i]); } csv.Write(values); csv.WriteLine(); }
public void Can_create_csv_from_Categories() { NorthwindData.LoadData(false); var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null); var categories = new[] { category, category }; var csv = CsvSerializer.SerializeToCsv(categories); Log(csv); Assert.That(csv, Is.EqualTo( "Id,CategoryName,Description,Picture\r\n" + "1,\"between \"\"quotes\"\" here\",\"with, comma\",\r\n" + "1,\"between \"\"quotes\"\" here\",\"with, comma\",\r\n" )); }
public static void SerializeToCsvFile(string filename, object data) { try { using (var writer = new StreamWriter(filename)) { CsvSerializer.SerializeToWriter(data, writer); } } catch (Exception ex) { Logger.LogError(ex.Message); } }
static void Main(string[] args) { CsvSerializer serializer = new CsvSerializer(); //string FilePath = @"C:\temp\KCw\Sep 2019\IIS Analysis\us-wclclaweb03\W3SVC8989\u_ex190901.log"; //IIS2CSV(FilePath); string folderPath = @"<folder which contains .log files>"; foreach (string filePath in Directory.GetFiles(folderPath, "*.log")) { IIS2CSV(filePath); } Console.WriteLine("Hello World!"); }
/// <summary> /// 加载本地的Asset.info /// </summary> private List <AssetItem> LoadLocalAssetInfo(RuntimePlatform platform) { var retList = new List <AssetItem>(); //优先加载persistent的Assets.info var persistentAssetInfoPath = BResources.GetAssetsInfoPath(BApplication.persistentDataPath, platform); if (File.Exists(persistentAssetInfoPath)) { var content = File.ReadAllText(persistentAssetInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } //streaming 和其他的Assets.info else { //根据加载模式不同,寻找不同目录下的其他配置 //打包时,本地会带一份ServerAssets.info以标记当前包携带的资源 var loadArtRoot = BDLauncher.Inst.GameConfig.ArtRoot; switch (loadArtRoot) { case AssetLoadPathType.Persistent: case AssetLoadPathType.StreamingAsset: { //TODO :BSA 读取,不需要Streaming前缀 var steamingAssetsInfoPath = IPath.Combine(BApplication.GetPlatformPath(platform), BResources.ASSETS_INFO_PATH); //var steamingAssetsInfoPath = GetAssetsInfoPath(BDApplication.streamingAssetsPath, platform); if (BetterStreamingAssets.FileExists(steamingAssetsInfoPath)) { var content = BetterStreamingAssets.ReadAllText(steamingAssetsInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } } break; case AssetLoadPathType.DevOpsPublish: { var path = GameConfig.GetLoadPath(loadArtRoot); var devopsAssetInfoPath = BResources.GetAssetsInfoPath(path, platform); if (File.Exists(devopsAssetInfoPath)) { var content = File.ReadAllText(devopsAssetInfoPath); retList = CsvSerializer.DeserializeFromString <List <AssetItem> >(content); } } break; } } return(retList); }
public void CsvSerializer_Serialize_SimpleObject_Test() { // Arrange var simpleObject = new SimpleObject { Id = 27, Name = "Simple Object 27" }; var csvSerializer = new CsvSerializer(); var expected = "27,Simple Object 27"; // Act var actual = csvSerializer.Serialize(simpleObject); // Assert Assert.AreEqual(expected, actual); }
public void TestHeaderEnabledByDefault() { var Output = new MemoryStream(); using (var Writer = new StreamWriter(Output, System.Text.Encoding.ASCII, 1024, true)) { CsvSerializer.Serialize(Writer, PropertyBasedData); } Output.Seek(0, 0); var Actual = new StreamReader(Output).ReadToEnd(); string Expected = "Prop1,Prop2(\r\n|\n)Hello,World(\r\n|\n)Good to,See you"; Assert.Matches(Expected, Actual); }
public void Can_create_csv_from_Categories_pipe_separator() { CsvConfig.ItemSeperatorString = "|"; NorthwindData.LoadData(false); var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null); var categories = new[] { category, category }; var csv = CsvSerializer.SerializeToCsv(categories); Log(csv); Assert.That(csv, Is.EqualTo( "Id|CategoryName|Description|Picture\r\n" + "1|\"between \"\"quotes\"\" here\"|with, comma|\r\n" + "1|\"between \"\"quotes\"\" here\"|with, comma|\r\n" )); }
public void Can_create_csv_from_Categories_long_delimiter() { CsvConfig.ItemDelimiterString = "~^~"; NorthwindData.LoadData(false); var category = NorthwindFactory.Category(1, "between \"quotes\" here", "with, comma", null); var categories = new[] { category, category }; var csv = CsvSerializer.SerializeToCsv(categories); Log(csv); Assert.That(csv, Is.EqualTo( "Id,CategoryName,Description,Picture\r\n" + "1,between \"quotes\" here,~^~with, comma~^~,\r\n" + "1,between \"quotes\" here,~^~with, comma~^~,\r\n" )); }
public override void Write(List <Control> controls) { StreamWriter fs = new StreamWriter(PathToFile); fs.Write(CsvSerializer.SerializeToCsv(GetListOfLines(controls))); fs.WriteLine("^"); fs.Write(CsvSerializer.SerializeToCsv(GetListOfEllipses(controls))); fs.WriteLine("^"); fs.Write(CsvSerializer.SerializeToCsv(GetListOfRects(controls))); fs.WriteLine("^"); fs.Write(CsvSerializer.SerializeToCsv(GetListOfCurvedRects(controls))); fs.WriteLine("^"); fs.Write(CsvSerializer.SerializeToCsv(GetListOfMultilines(controls))); fs.Dispose(); }
public void OnTimedEvent(object source, ElapsedEventArgs e) { Singleton.merged[next_to_show].czas = -1; try { using (var stream = new FileStream("Kombinacje.csv", FileMode.Create, FileAccess.Write)) { var cs = new CsvSerializer<Kombinacja>() { UseTextQualifier = true, }; cs.Serialize(stream, Singleton.merged); } } catch (Exception sse) { } next_to_show++; zapal(); }
private void button1_Click(object sender, EventArgs e) { Singleton.dane = new Dane(); Singleton.dane.pseudonim = textBox2.Text; Singleton.dane.wiek = (int)numericUpDown1.Value; Singleton.dane.plec = domainUpDown1.SelectedIndex; List<Dane> lista = new List<Dane>(); lista.Add(Singleton.dane); using (var stream = new FileStream("Dane.csv", FileMode.Create, FileAccess.Write)) { var cs = new CsvSerializer<Dane>() { UseTextQualifier = true, }; cs.Serialize(stream, lista); } Hide(); eks = new Eksperyment(); eks.FormClosing += (s, ec) => Close(); eks.Show(); }
public void SerializeFooListWithPipe() { var serializer = new CsvSerializer<Foo>("|"); var actual = DongleEncoding.Default.GetString(serializer.Serialize(Foo.FooArray)); Assert.AreEqual(CsvWithPipeExpected, actual); }
public void SerializeFooListWithResourceAndCulture() { var serializer = new CsvSerializer<Foo>(FooResource.ResourceManager); var actual = DongleEncoding.Default.GetString(serializer.Serialize(Foo.FooArray, CultureInfo.GetCultureInfo("pt-BR"))); Assert.AreEqual(CsvExpectedWithResource, actual); }
private void Form2_KeyDown(object sender, KeyEventArgs e) { if (Singleton.ustawienia.tryb == 1) { if (e.KeyCode == Keys.D1 && !zapalone[1]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D2 && !zapalone[2]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D3 && !zapalone[3]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D4 && !zapalone[4]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D5 && !zapalone[5]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D6 && !zapalone[6]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D7 && !zapalone[7]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D8 && !zapalone[8]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D9 && !zapalone[9]) { System.Media.SystemSounds.Beep.Play(); } if (e.KeyCode == Keys.D0 && !zapalone[0]) { System.Media.SystemSounds.Beep.Play(); } } bool zmiana = false; if (e.KeyCode == Keys.D1 && zapalone[1]) { zmiana = true; } if (e.KeyCode == Keys.D2 && zapalone[2]) { zmiana = true; } if (e.KeyCode == Keys.D3 && zapalone[3]) { zmiana = true; } if (e.KeyCode == Keys.D4 && zapalone[4]) { zmiana = true; } if (e.KeyCode == Keys.D5 && zapalone[5]) { zmiana = true; } if (e.KeyCode == Keys.D6 && zapalone[6]) { zmiana = true; } if (e.KeyCode == Keys.D7 && zapalone[7]) { zmiana = true; } if (e.KeyCode == Keys.D8 && zapalone[8]) { zmiana = true; } if (e.KeyCode == Keys.D9 && zapalone[9]) { zmiana = true; } if (e.KeyCode == Keys.D0 && zapalone[0]) { zmiana = true; } if (zmiana) { if (Singleton.ustawienia.subtryb == 1) { timer.Stop(); timer.Start(); } } if (e.KeyCode == Keys.D1) { zapalone[1] = false; pictureBox1.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D2) { zapalone[2] = false; pictureBox2.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D3) { zapalone[3] = false; pictureBox3.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D4) { zapalone[4] = false; pictureBox4.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D5) { zapalone[5] = false; pictureBox5.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D6) { zapalone[6] = false; pictureBox6.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D7) { zapalone[7] = false; pictureBox7.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D8) { zapalone[8] = false; pictureBox8.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D9) { zapalone[9] = false; pictureBox9.Image = Properties.Resources.L11; } if (e.KeyCode == Keys.D0) { zapalone[0] = false; pictureBox10.Image = Properties.Resources.L11; } bool jest_zapalona = false; if (zapalone[1]) jest_zapalona = true; if (zapalone[2]) jest_zapalona = true; if (zapalone[3]) jest_zapalona = true; if (zapalone[4]) jest_zapalona = true; if (zapalone[5]) jest_zapalona = true; if (zapalone[6]) jest_zapalona = true; if (zapalone[7]) jest_zapalona = true; if (zapalone[8]) jest_zapalona = true; if (zapalone[9]) jest_zapalona = true; if (zapalone[0]) jest_zapalona = true; if (!jest_zapalona) { sw.Stop(); Singleton.merged[next_to_show].czas = (int)sw.ElapsedMilliseconds; using (var stream = new FileStream("Kombinacje.csv", FileMode.Create, FileAccess.Write)) { var cs = new CsvSerializer<Kombinacja>() { UseTextQualifier = true, }; cs.Serialize(stream, Singleton.merged); } next_to_show++; if (next_to_show >= Singleton.merged.Count) { MessageBox.Show(Singleton.ustawienia.podziekowanie); //Application.Exit(); } zapal(); timer.Stop(); timer.Start(); } }
public void SerializeDicionary() { var serializer = new CsvSerializer<Dictionary<string, object>>(); var actual = DongleEncoding.Default.GetString(serializer.Serialize(Foo.FooDictionary)); Assert.AreEqual(CsvExpected, actual); }