Esempio n. 1
0
 protected override void Act()
 {
     using (Reader)
     {
         Document = CsvDocument.CreateFrom(Reader, Options);
     }
 }
Esempio n. 2
0
        public void ToStringTest1()
        {
            var format   = new CsvFormat(';', '"');
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            Assert.AreEqual(
                "Name;Age\r\n" +
                "Akari;20\r\n" +
                "Kyoko;21\r\n" +
                "Yui;22\r\n" +
                "Chinatsu;19\r\n", document.ToString(format));
        }
Esempio n. 3
0
        public void ToStringTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            Assert.AreEqual(
                "Name,Age\r\n" +
                "Akari,20\r\n" +
                "Kyoko,21\r\n" +
                "Yui,22\r\n" +
                "Chinatsu,19\r\n", document.ToString());
        }
Esempio n. 4
0
        public void ContainsTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            Assert.IsTrue(document.Contains(new Person {
                Name = "Akari", Age = 20
            }));
            Assert.IsTrue(document.Contains(new Person {
                Name = "Kyoko", Age = 21
            }));
            Assert.IsTrue(document.Contains(new Person {
                Name = "Yui", Age = 22
            }));
            Assert.IsTrue(document.Contains(new Person {
                Name = "Chinatsu", Age = 19
            }));
        }
Esempio n. 5
0
        public void GetEnumeratorTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
            });

            var enumerator = document.GetEnumerator();

            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(CsvRecord.From(new { Name = "Akari", Age = 20 }), enumerator.Current);

            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(CsvRecord.From(new { Name = "Kyoko", Age = 21 }), enumerator.Current);

            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(CsvRecord.From(new { Name = "Yui", Age = 22 }), enumerator.Current);

            Assert.IsFalse(enumerator.MoveNext());
        }
Esempio n. 6
0
        public void Must_FilterOutTheRows_UsingTheLowerLevelRowFilter(
            IList <string[]> rows)
        {
            var expectedRows = rows.ToArray();

            var document = new CsvDocument
            {
                ContentRows = expectedRows,
                HeaderCells = new string[0]
            };

            target.Transform(document, rowMatchEvaluator.Object);

            rowFilter.Verify(
                x => x.Filter(
                    It.Is <string[][]>(
                        arg => arg == expectedRows),
                    It.IsAny <Filtering.IRowMatchEvaluator>()),
                Times.Once,
                "Must run use the filter component, and pass the rows onto it");

            rowFilter.Verify(
                x => x.Filter(
                    It.IsAny <string[][]>(),
                    It.Is <Filtering.IRowMatchEvaluator>(
                        arg => arg == rowMatchEvaluator.Object)),
                "Must run pass the match evaluator on to the filter component");
        }
Esempio n. 7
0
        public void WriteContentsToFileTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            using (var tempFile = new TempFile())
            {
                document.WriteContentsToFile(tempFile.FullName);

                using var reader = new StreamReader(tempFile.FullName);
                Assert.AreEqual(
                    "Name,Age\r\n" +
                    "Akari,20\r\n" +
                    "Kyoko,21\r\n" +
                    "Yui,22\r\n" +
                    "Chinatsu,19\r\n", reader.ReadToEnd());
            }
        }
Esempio n. 8
0
        public void WriteFieldsTest()
        {
            var document = new CsvDocument(new[] { "Name", "Age" });

            document.WriteFields(b =>
            {
                b.AddField("Carlos");
                b.AddField(20);
            });

            document.WriteFields(b =>
            {
                b.AddField("Age", 30);
                b.AddField("Name", "Maria");
            });

            Assert.AreEqual("Name,Age\r\n" +
                            "Carlos,20\r\n" +
                            "Maria,30\r\n", document.ToString());

            Assert.Throws <ArgumentException>(() =>
            {
                document.WriteFields(b =>
                {
                    b.AddField("Name", "Kara");
                    b.AddField("Age", 17);
                    b.AddField("LastName", "Li");
                });
            });
        }
Esempio n. 9
0
        private static async Task RunAsync(string orgName, string outputFileName, string cacheLocation)
        {
            var isForExcel = outputFileName == null;

            var client = await GitHubClientFactory.CreateAsync();

            var cachedOrg = await CachedOrg.LoadAsync(client, orgName, Console.Out, cacheLocation, forceUpdate : false);

            var csvDocument = new CsvDocument("repo", "repo-state", "repo-last-pushed", "principal-kind", "principal", "permission", "via-team");

            using (var writer = csvDocument.Append())
            {
                foreach (var repo in cachedOrg.Repos)
                {
                    var publicPrivate = repo.IsPrivate ? "private" : "public";
                    var lastPush      = repo.LastPush.ToLocalTime().DateTime.ToString();

                    foreach (var teamAccess in repo.Teams)
                    {
                        var permissions = teamAccess.Permission.ToString().ToLower();
                        var teamName    = teamAccess.Team.Name;
                        var teamUrl     = teamAccess.Team.Url;

                        writer.WriteHyperlink(repo.Url, repo.Name, isForExcel);
                        writer.Write(publicPrivate);
                        writer.Write(lastPush);
                        writer.Write("team");
                        writer.WriteHyperlink(teamUrl, teamName, isForExcel);
                        writer.Write(permissions);
                        writer.Write(teamName);
                        writer.WriteLine();
                    }

                    foreach (var userAccess in repo.Users)
                    {
                        var via         = userAccess.Describe().ToString();
                        var userUrl     = CachedOrg.GetUserUrl(userAccess.UserLogin);
                        var permissions = userAccess.Permission.ToString().ToLower();

                        writer.WriteHyperlink(repo.Url, repo.Name, isForExcel);
                        writer.Write(publicPrivate);
                        writer.Write(lastPush);
                        writer.Write("user");
                        writer.WriteHyperlink(userUrl, userAccess.UserLogin, isForExcel);
                        writer.Write(permissions);
                        writer.Write(via);
                        writer.WriteLine();
                    }
                }
            }

            if (outputFileName == null)
            {
                csvDocument.ViewInExcel();
            }
            else
            {
                csvDocument.Save(outputFileName);
            }
        }
Esempio n. 10
0
        public void RemoveAllTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            Assert.AreEqual(4, document.Count);
            Assert.AreEqual(2, document.RemoveAll(e => e.Age > 20));
            Assert.AreEqual(2, document.Count);


            Assert.AreEqual(new CsvRecord(document.Header, new string[] { "Akari", "20" }), document[0]);
            Assert.AreEqual(new CsvRecord(document.Header, new string[] { "Chinatsu", "19" }), document[1]);
        }
Esempio n. 11
0
        public void Must_RunTheTransformation_UsingATransformationRunner_WithAGivenDocument_AndTheFreshlyBuiltTransformer(
            IDictionary <string, int> columnMap)
        {
            var document = new CsvDocument
            {
                HeaderCells = new string[0],
                ContentRows = new string[0][]
            };

            Setup_ColumnIndexMapBuilder(columnMap);

            IRowTransformer rowTransformer = new Mock <IRowTransformer>().Object;

            Setup_TransformerFactory(rowTransformer);

            target.Transform(document);

            transformerRunner.Verify(
                x => x.Transform(
                    It.Is <CsvDocument>(
                        arg => arg == document),
                    It.IsAny <IRowTransformer>()),
                Times.Once,
                "Must pass the original CSV document onto the transformation runner thing");

            transformerRunner.Verify(
                x => x.Transform(
                    It.Is <CsvDocument>(
                        arg => arg == document),
                    It.Is <IRowTransformer>(
                        arg => arg == rowTransformer)),
                Times.Once,
                "Must pass the brand new freshly-built CSV row transformer onto the transformation runner thing");
        }
        public void Must_FirstTransformHeader_RegardlessOfWhetherThereAreColumnsDefined(
            IList <string> columns)
        {
            //i want to check that Header was transformed before it attempted to transform the content
            GetSetup_TransformationRunner()
            .Throws <NonWelcomeInvocatioException>();

            var document = new CsvDocument
            {
                ContentRows = new string[][] { new string[] { "one" } },
                HeaderCells = columns.ToArray()
            };

            try
            {
                target.Transform(document, transformer.Object);
            }
            catch (NonWelcomeInvocatioException)
            {
            }

            transformer.Verify(
                x => x.TransformHeader(
                    It.IsAny <string[]>()),
                Times.Once,
                "Must transform the Header before transforming the content");
        }
Esempio n. 13
0
        public void LastIndexOfTest()
        {
            var document = new CsvDocument <Person>(new Person[]
            {
                new Person {
                    Name = "Akari", Age = 20
                },
                new Person {
                    Name = "Kyoko", Age = 21
                },
                new Person {
                    Name = "Yui", Age = 22
                },
                new Person {
                    Name = "Chinatsu", Age = 19
                }
            });

            Assert.AreEqual(0, document.LastIndexOf(new Person {
                Name = "Akari", Age = 20
            }));
            Assert.AreEqual(1, document.LastIndexOf(new Person {
                Name = "Kyoko", Age = 21
            }));
            Assert.AreEqual(2, document.LastIndexOf(new Person {
                Name = "Yui", Age = 22
            }));
            Assert.AreEqual(3, document.LastIndexOf(new Person {
                Name = "Chinatsu", Age = 19
            }));

            Assert.AreEqual(-1, document.LastIndexOf(new Person {
                Name = "Ayano", Age = 19
            }));
        }
Esempio n. 14
0
 protected override void ReportDifferences(CsvDocument before, CsvDocument after)
 {
     if (HaveHeaderCellsChanged(before.HeaderCells, after.HeaderCells))
     {
         stringWriter.WriteLine("Columns have been added/removed. The document is now made up of these columns:");
         stringWriter.WriteLine($"* {Stringicize(after.HeaderCells)}");
     }
 }
Esempio n. 15
0
        public Stream Go(Stream source, char delimiter)
        {
            CsvDocument document = csvReader.Read(source);

            CsvDocument result = transformer.Transform(document);

            return(WriteToCsvStream(result, delimiter));
        }
Esempio n. 16
0
        private static void SaveVioloations(string orgName, string outputFileName, bool isForExcel, IReadOnlyList <PolicyViolation> violations)
        {
            var csvDocument = new CsvDocument("org", "severity", "rule", "rule-title", "fingerprint", "violation", "repo", "user", "team", "assignees");

            using (var writer = csvDocument.Append())
            {
                foreach (var violation in violations)
                {
                    writer.Write(orgName);
                    writer.Write(violation.Descriptor.Severity.ToString());
                    writer.Write(violation.Descriptor.DiagnosticId);
                    writer.Write(violation.Descriptor.Title);
                    writer.Write(violation.Fingerprint.ToString());
                    writer.Write(violation.Title);

                    if (violation.Repo == null)
                    {
                        writer.Write(string.Empty);
                    }
                    else
                    {
                        writer.WriteHyperlink(violation.Repo.Url, violation.Repo.Name, isForExcel);
                    }

                    if (violation.User == null)
                    {
                        writer.Write(string.Empty);
                    }
                    else
                    {
                        writer.WriteHyperlink(violation.User.Url, violation.User.Login, isForExcel);
                    }

                    if (violation.Team == null)
                    {
                        writer.Write(string.Empty);
                    }
                    else
                    {
                        writer.WriteHyperlink(violation.Team.Url, violation.Team.Name, isForExcel);
                    }

                    var assignees = string.Join(", ", violation.Assignees.Select(r => r.Login));
                    writer.Write(assignees);

                    writer.WriteLine();
                }
            }

            if (outputFileName == null)
            {
                csvDocument.ViewInExcel();
            }
            else
            {
                csvDocument.Save(outputFileName);
            }
        }
Esempio n. 17
0
        public void ToStringTest()
        {
            var document = new CsvDocument(new string[] { "name", "age" });

            document.Write("Light", 18);
            document.Write("Misa", 20);

            Assert.AreEqual("name,age\r\nLight,18\r\nMisa,20\r\n", document.ToString());
        }
Esempio n. 18
0
        public void CsvDocumentTest2()
        {
            var document = new CsvDocument(new string[] { "name", "age" }, flexible: true);

            Assert.AreEqual(CsvHeader.FromValues("name", "age"), document.Header);
            Assert.IsTrue(document.IsFlexible);
            Assert.IsTrue(document.IsEmpty);
            Assert.AreEqual(0, document.Count);
        }
        public CsvDocument Transform(CsvDocument document)
        {
            foreach (var rewriter in transformers)
            {
                document = rewriter.Transform(document);
            }

            return(document);
        }
Esempio n. 20
0
        public void CsvDocumentTest()
        {
            var document = new CsvDocument <Person>();

            Assert.AreEqual(0, document.Count);
            Assert.IsTrue(document.IsEmpty);
            Assert.AreEqual(CsvHeader.FromValues("Name", "Age"), document.Header);
            Assert.AreEqual(CsvFormat.Default, document.Format);
        }
        public void ProcessDirectory(string directory, Action <string> Log)
        {
            Log("Obteniendo los archivos a procesar...");

            string[] files = Directory.GetFiles(directory, "*.xml",
                                                SearchOption.AllDirectories);

            Log(string.Format("Encontre [{0}] archivos", files.Length));

            CsvDocument csv = new CsvDocument();

            csv.HeaderColumns.Add("FacturaArchivo");
            csv.HeaderColumns.Add("EmisorNombre");
            csv.HeaderColumns.Add("EmisorRfc");
            csv.HeaderColumns.Add("ImpuestosTotal");
            csv.HeaderColumns.Add("ImpuestosIvaTasa");
            csv.HeaderColumns.Add("ImpuestosIvaImporte");
            csv.HeaderColumns.Add("TipoIngreso");
            csv.HeaderColumns.Add("Total");
            csv.HeaderColumns.Add("Descuento");
            csv.HeaderColumns.Add("SubTotal");
            csv.HeaderColumns.Add("FormaPago");
            csv.HeaderColumns.Add("Fecha");

            var data = csv.Table;

            XmlSerializer serializer = new XmlSerializer(typeof(Comprobante));

            foreach (string file in files)
            {
                Log($"Procesando archivo: {file}");
                using (StreamReader reader = new StreamReader(file))
                {
                    Comprobante record = (Comprobante)serializer.Deserialize(reader);

                    data.Add(new List <string>()
                    {
                        Path.GetFileNameWithoutExtension(file) ?? string.Empty,
                        record.Emisor.Nombre ?? string.Empty,
                        record.Emisor.Rfc ?? string.Empty,
                        record.Impuestos.TotalImpuestosTrasladados ?? string.Empty,
                        GetImpuesto("IVA", record.Impuestos).Tasa ?? string.Empty,
                        GetImpuesto("IVA", record.Impuestos).Importe ?? string.Empty,
                        record.Fecha ?? string.Empty,
                        record.FormaDePago ?? string.Empty,
                        record.Descuento ?? string.Empty,
                        record.TipoDeComprobante ?? string.Empty,
                        record.SubTotal ?? string.Empty,
                        record.Total ?? string.Empty
                    });
                }
            }

            var reportPath = Path.Combine(directory, "Reporte.csv");

            csv.Save(reportPath, true);
        }
Esempio n. 22
0
        public override IEnumerable <string> Execute(CsvDocument value, DependencyDataSource dependencyDataSource)
        {
            var resultBuilder = new StringBuilder();

            using (var stringWriter = new StringWriter(resultBuilder))
            {
                using (var writer = new CsvWriter(stringWriter, new Configuration
                {
                    Delimiter = _outputDelimiter
                }))
                {
                    // Names could repeat to support alternative column calculation methods
                    foreach (var column in _columnsOrder)
                    {
                        writer.WriteField(column);
                    }

                    foreach (var row in value.Rows)
                    {
                        writer.NextRecord();

                        foreach (var columnTransitionName in _columnsOrder)
                        {
                            string resultColumnValue = null;

                            foreach (var columnTransitionOption in _columnTransitions[columnTransitionName])
                            {
                                string sourceColumnValue = null;
                                if (columnTransitionOption.SourceName != null && value.Columns.Contains(columnTransitionOption.SourceName))
                                {
                                    var sourceColumnIndex = value.Columns.IndexOf(columnTransitionOption.SourceName);
                                    sourceColumnValue = row[sourceColumnIndex] as string;

                                    foreach (var postProcessor in columnTransitionOption.PostProcessors)
                                    {
                                        sourceColumnValue = postProcessor.Execute(sourceColumnValue, dependencyDataSource).SingleOrDefault();
                                    }
                                }

                                resultColumnValue = sourceColumnValue ?? dependencyDataSource.Resolve(columnTransitionOption.Value);
                                if (resultColumnValue != null)
                                {
                                    break;
                                }
                            }

                            if (resultColumnValue != null)
                            {
                                writer.WriteField(resultColumnValue);
                            }
                        }
                    }
                }
            }

            yield return(resultBuilder.ToString());
        }
Esempio n. 23
0
        public Stream Compare(
            Stream source1,
            Stream source2,
            char reportValueDelimiter)
        {
            CsvDocument doc1 = Read(
                csvStream1Reader,
                1,
                source1);

            CsvDocument doc2 = Read(
                csvStream2Reader,
                2,
                source2);

            doc1 = TransformWithErrorHandling(doc1, transformer1, 1);
            doc2 = TransformWithErrorHandling(doc2, transformer2, 2);

            var comparer = BuildComparer(doc1.HeaderCells, doc2.HeaderCells);

            ComparisonResult result;

            try
            {
                result = comparer.Compare(
                    doc1.ContentRows,
                    doc2.ContentRows);
            }
            catch (InputParsingException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new DataComparisonException(e);
            }

            var stringyfyer = new Andy.Csv.Serialization.RowStringifier(
                new Andy.Csv.Serialization.CellValueEncoder());

            try
            {
                string[] lines = ResultStringification.StringyfyyResults(
                    result,
                    doc1.HeaderCells,
                    doc2.HeaderCells,
                    reportValueDelimiter,
                    stringyfyer);

                return(CsvFileWriter.Write(lines));
            }
            catch (Exception e)
            {
                throw new ReportProductionException(e);
            }
        }
Esempio n. 24
0
        public void CsvDocumentTest()
        {
            var document = new CsvDocument(new string[] { "name", "age" });

            Assert.AreEqual(CsvHeader.FromValues("name", "age"), document.Header);
            Assert.AreEqual(CsvFormat.Default, document.Format);
            Assert.IsFalse(document.IsFlexible);
            Assert.IsTrue(document.IsEmpty);
            Assert.AreEqual(0, document.Count);
        }
Esempio n. 25
0
        public void UpdateWithTest()
        {
            var document = new CsvDocument(new string[] { "name", "age" });

            document.WriteWith(new { Name = "Light", Age = "18" });
            document.WriteWith(new { Name = "Misa", Age = "20" });

            document.UpdateWith(1, new { Name = "Misa", Age = 17 });
            Assert.AreEqual(2, document.Count);
        }
Esempio n. 26
0
        public void MutateAtTest()
        {
            var document = new CsvDocument(new string[] { "name", "age" });

            document.Write("Light", 18);
            document.Write("Misa", 20);

            document.MutateAt(0, record => record.Update("name", "Light Yagami"));
            Assert.AreEqual("Light Yagami,18", document[0].ToString());
        }
Esempio n. 27
0
        public void ToStringTest1()
        {
            var format   = new CsvFormat(';', '\"');
            var document = new CsvDocument(new string[] { "name", "age" }, format);

            document.Write("Light", 18);
            document.Write("Misa", 20);

            Assert.AreEqual("name;age\r\nLight;18\r\nMisa;20\r\n", document.ToString(format));
        }
Esempio n. 28
0
        public void WriteAllTest()
        {
            var document = new CsvDocument(new string[] { "name", "age" });

            document.WriteAll(new string[] { "Light", "18" });
            document.WriteAll(new string[] { "Misa", "20" });

            Assert.IsFalse(document.IsEmpty);
            Assert.AreEqual(2, document.Count);
        }
Esempio n. 29
0
        private string[][] CombineColumnAndDataRows(CsvDocument document)
        {
            var allRows = new string[document.ContentRows.Length + 1][];

            allRows[0] = document.HeaderCells;

            document.ContentRows.CopyTo(allRows, 1);

            return(allRows);
        }
Esempio n. 30
0
        public void CsvDocumentTest1()
        {
            var format   = new CsvFormat(';', '\"');
            var document = new CsvDocument <Person>(format);

            Assert.AreEqual(0, document.Count);
            Assert.IsTrue(document.IsEmpty);
            Assert.AreEqual(CsvHeader.FromValues(format, "Name", "Age"), document.Header);
            Assert.AreEqual(new CsvFormat(';', '\"'), document.Format);
        }
Esempio n. 31
0
        public MainWindow()
        {
            InitializeComponent();
            earth.Radius = FlightVisual3D.EarthRadius;
            Loaded += MainWindowLoaded;
            Flights = new ObservableCollection<FlightVisual3D>();

            var doc = new CsvDocument<Airport>();
            doc.Load(Application.GetResourceStream(new Uri("pack://application:,,,/Examples/Flights/airports.csv")).Stream);
            Airports = doc.Items;

            DataContext = this;
        }
Esempio n. 32
0
        // todo: convert to MVVM

        public MainWindow()
        {
            InitializeComponent();
            earth.Radius = FlightVisual3D.EarthRadius;
            Loaded += MainWindowLoaded;
            Flights = new ObservableCollection<FlightVisual3D>();

            var doc = new CsvDocument<Airport>();
            doc.Load("airports.csv");
            Airports = doc.Items;

            DataContext = this;
        }