Exemple #1
0
        public void ChangeMemberMapTest()
        {
            var config = new CsvHelper.Configuration.Configuration();
            var map    = config.AutoMap <A>();

            map.Map(m => m.B.C.P3).Index(3);
        }
Exemple #2
0
        public void AutoMapWithExistingMapTest()
        {
            var config      = new CsvHelper.Configuration.Configuration();
            var existingMap = new SimpleMap();

            config.Maps.Add(existingMap);
            var data = new
            {
                Simple = new Simple
                {
                    Id   = 1,
                    Name = "one"
                }
            };
            var map = config.AutoMap(data.GetType());

            Assert.IsNotNull(map);
            Assert.AreEqual(0, map.MemberMaps.Count);
            Assert.AreEqual(1, map.ReferenceMaps.Count);

            // Since Simple is a reference on the anonymous object, the type won't
            // be re-used. Types which are created from automapping aren't added
            // to the list of registered maps either.
            Assert.IsNotInstanceOfType(map.ReferenceMaps[0].Data.Mapping, typeof(SimpleMap));
        }
Exemple #3
0
        public void CommentThatCrossesBuffersShouldNotAddToFieldTest()
        {
            var config = new CsvHelper.Configuration.Configuration
            {
                AllowComments = true,
                BufferSize    = 10
            };

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var parser = new CsvParser(reader, config))
                        {
                            parser.Configuration.Delimiter = ",";
                            writer.Write("1,2\r\n");
                            writer.Write("#commented line\r\n");
                            writer.Write("3,4");
                            writer.Flush();
                            stream.Position = 0;

                            parser.Read();
                            var line = parser.Read();
                            Assert.AreEqual("3", line[0]);
                            Assert.AreEqual("4", line[1]);
                        }
        }
        public void ConvertWithIndexEndTest()
        {
            var config = new CsvHelper.Configuration.Configuration {
                HasHeaderRecord = false
            };
            var rowMock       = new Mock <IReaderRow>();
            var currentRecord = new[] { "1", "one", "1", "2", "3" };
            var context       = new ReadingContext(new StringReader(string.Empty), config, false)
            {
                Record = currentRecord
            };

            rowMock.Setup(m => m.Configuration).Returns(config);
            rowMock.Setup(m => m.Context).Returns(context);
            rowMock.Setup(m => m.GetField(It.IsAny <Type>(), It.IsAny <int>())).Returns <Type, int>((type, index) => Convert.ToInt32(currentRecord[index]));
            var data = new MemberMapData(typeof(Test).GetProperty("List"))
            {
                Index    = 2,
                IndexEnd = 3
            };

            data.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture;

            var converter  = new IEnumerableGenericConverter();
            var enumerable = (IEnumerable <int?>)converter.ConvertFromString("1", rowMock.Object, data);
            var list       = enumerable.ToList();

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual(1, list[0]);
            Assert.AreEqual(2, list[1]);
        }
        public static Configuration GetConfiguration(string datatypeName)
        {
            var conf = new CsvHelper.Configuration.Configuration()
            {
                Delimiter       = ",",
                HasHeaderRecord = false
            };

            switch (datatypeName.ToLower())
            {
            case "parametres":
                conf.Delimiter = "\t";
                conf.RegisterClassMap <Parametres.ParametersMap>();
                return(conf);

            case "data":
                conf.RegisterClassMap <Data.DataMap>();
                return(conf);

            case "dataindicbruit":
                conf.RegisterClassMap <Dataindicbruit.DataindicbruitMap>();
                return(conf);

            default:
                throw new Exception($"bad type name : the parsing of the type {datatypeName} is not implemented");
            }
        }
Exemple #6
0
        public void MultipleCharDelimiterWithBufferEndingInMiddleOfDelimiterTest()
        {
            var config = new CsvHelper.Configuration.Configuration
            {
                Delimiter  = "|~|",
                BufferSize = 3,
            };

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var parser = new CsvParser(reader, config))
                        {
                            writer.WriteLine("1|~|2");
                            writer.Flush();
                            stream.Position = 0;

                            var row = parser.Read();
                            Assert.IsNotNull(row);
                            Assert.AreEqual(2, row.Length);
                            Assert.AreEqual("1", row[0]);
                            Assert.AreEqual("2", row[1]);
                            row = parser.Read();
                            Assert.IsNull(row);
                        }
        }
        public void ConvertWithIndexEndTest()
        {
            var config = new CsvHelper.Configuration.Configuration {
                HasHeaderRecord = false
            };
            var rowMock       = new Mock <IReaderRow>();
            var headers       = new[] { "Id", "Name", "Prop1", "Prop2", "Prop3" };
            var currentRecord = new[] { "1", "One", "1", "2", "3" };
            var context       = new ReadingContext(new StringReader(string.Empty), config, false)
            {
                HeaderRecord = headers,
                Record       = currentRecord
            };

            rowMock.Setup(m => m.Configuration).Returns(config);
            rowMock.Setup(m => m.Context).Returns(context);
            rowMock.Setup(m => m.GetField(It.IsAny <Type>(), It.IsAny <int>())).Returns <Type, int>((type, index) => Convert.ToInt32(currentRecord[index]));
            var data = new MemberMapData(typeof(Test).GetProperty("Dictionary"))
            {
                Index    = 2,
                IndexEnd = 3
            };

            data.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture;

            var converter  = new IDictionaryGenericConverter();
            var dictionary = (IDictionary)converter.ConvertFromString("1", rowMock.Object, data);

            Assert.AreEqual(2, dictionary.Count);
            Assert.AreEqual(1, dictionary["Prop1"]);
            Assert.AreEqual(2, dictionary["Prop2"]);
        }
Exemple #8
0
        public void CircularDependencyWithMultiplePropertiesTest()
        {
            var config = new CsvHelper.Configuration.Configuration();
            var map    = config.AutoMap <A>();

            Assert.AreEqual(1, map.MemberMaps.Count);
            Assert.AreEqual(3, map.ReferenceMaps.Count);
        }
        public void AddingMappingsWithGenericMethod2Test()
        {
            var config = new CsvHelper.Configuration.Configuration();

            config.RegisterClassMap <TestClassMappings>();

            Assert.AreEqual(2, config.Maps[typeof(TestClass)].MemberMaps.Count);
        }
        public void AddingMappingsWithInstanceMethodTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            config.RegisterClassMap(new TestClassMappings());

            Assert.AreEqual(2, config.Maps[typeof(TestClass)].MemberMaps.Count);
        }
Exemple #11
0
        public CSVBridge(Configuration config, ClassMap map = null)
        {
            _map    = map;
            _config = config;

            //override IgnoreReadingExceptions so we can do internal error management
            //_config.IgnoreReadingExceptions = true;
        }
        public void RegisterClassMapNonGenericTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            Assert.IsNull(config.Maps[typeof(TestClass)]);
            config.RegisterClassMap(typeof(TestClassMappings));
            Assert.IsNotNull(config.Maps[typeof(TestClass)]);
        }
        public void RegisterClassInstanceTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            Assert.IsNull(config.Maps[typeof(TestClass)]);
            config.RegisterClassMap(new TestClassMappings());
            Assert.IsNotNull(config.Maps[typeof(TestClass)]);
        }
Exemple #14
0
        public void AutoMapWithDefaultConstructor()
        {
            var      config = new CsvHelper.Configuration.Configuration();
            ClassMap map    = config.AutoMap <SimpleReferenceHasNoDefaultConstructor>();

            Assert.AreEqual("Id", map.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Name", map.ReferenceMaps[0].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("name", map.ReferenceMaps[0].Data.Mapping.ParameterMaps[0].Data.Name);
        }
        public void PropertyMapAccessTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            config.RegisterClassMap <AMap>();
            config.Maps.Find <A>().Map(m => m.AId).Ignore();

            Assert.AreEqual(true, config.Maps[typeof(A)].MemberMaps[0].Data.Ignore);
        }
        static CSVHelper()
        {
            configuration = new CsvHelper.Configuration.Configuration()
            {
                CultureInfo = CultureInfo.InvariantCulture, HasHeaderRecord = false
            };

            configuration.TypeConverterCache.AddConverter <string[]>(new EnumerableConverter <string>());
        }
        public void MapMultipleTypesTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            config.RegisterClassMap <AMap>();
            config.RegisterClassMap <BMap>();

            Assert.IsNotNull(config.Maps[typeof(A)]);
            Assert.IsNotNull(config.Maps[typeof(B)]);
        }
            public APrivateMap()
            {
                var config = new CsvHelper.Configuration.Configuration
                {
                    IncludePrivateMembers = true,
                    MemberTypes           = MemberTypes.Fields
                };

                AutoMap(config);
            }
Exemple #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvDataSource" /> class.
        /// </summary>
        /// <param name="name">The source name.</param>
        /// <param name="connection">The connection.</param>
        /// <param name="filePattern">The file pattern.</param>
        /// <param name="mode">The file mode.</param>
        /// <param name="config">The CSV configuration.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
        public CsvDataSource(string name, DataConnection connection, string filePattern, FolderMode mode, Csv.Configuration config, IFileSystemService fileSystem)
        {
            this.name        = name ?? throw new ArgumentNullException("name");
            this.connection  = connection ?? throw new ArgumentNullException("connection");
            this.filePattern = filePattern ?? throw new ArgumentNullException("filePattern");
            this.config      = config ?? throw new ArgumentNullException("config");
            this.fileSystem  = fileSystem ?? throw new ArgumentNullException("fileSystem");

            this.mode = mode;
        }
Exemple #20
0
        public void AutoMapEnumerableTest()
        {
            var config = new CsvHelper.Configuration.Configuration();

            try
            {
                config.AutoMap(typeof(List <string>));
                Assert.Fail();
            }
            catch (ConfigurationException) {}
        }
Exemple #21
0
        public CSVBridge(ClassMap map = null, bool hasHeader = true)
        {
            _map    = map;
            _config = new Configuration()
            {
                HasHeaderRecord = hasHeader
            };

            //override IgnoreReadingExceptions so we can do internal error management
            //_config.IgnoreReadingExceptions = true;
        }
Exemple #22
0
 private static CsvHelper.Configuration.Configuration GetConfiguration()
 {
     if (CsvConfiguration == null)
     {
         CsvConfiguration = new CsvHelper.Configuration.Configuration(System.Globalization.CultureInfo.InvariantCulture)
         {
             MemberTypes = CsvHelper.Configuration.MemberTypes.Fields,
         };
     }
     return(CsvConfiguration);
 }
Exemple #23
0
        public void CircularDependencyTest()
        {
            var config = new CsvHelper.Configuration.Configuration();
            var map    = config.AutoMap <ACircular>();

            Assert.IsNotNull(map);
            Assert.AreEqual(1, map.MemberMaps.Count);
            Assert.AreEqual(1, map.ReferenceMaps.Count);
            Assert.AreEqual(1, map.ReferenceMaps[0].Data.Mapping.MemberMaps.Count);
            Assert.AreEqual(0, map.ReferenceMaps[0].Data.Mapping.ReferenceMaps.Count);
        }
Exemple #24
0
        /// <summary>
        /// Creates a CSV data reader from the files.
        /// </summary>
        /// <param name="files">The files to load.</param>
        /// <param name="config">The CSV configuration.</param>
        /// <returns>
        /// An IDataReader instance.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">If files is null.</exception>
        public IDataReader CreateDataReader(IEnumerable<IFileInfo> files, Csv.Configuration config)
        {
            if (files == null)
            {
                throw new ArgumentNullException("files");
            }

            var sourceFiles = 
                files.Zip(this.fileContents, (l, r) => new StringSourceFile(l.FullName, r));

            return new MultipleCsvDataReader(sourceFiles, config);
        }
Exemple #25
0
 public void EnsureInternalsAreSetupWhenPasingWriterAndConfigTest()
 {
     using (var stream = new MemoryStream())
         using (var writer = new StreamWriter(stream))
         {
             var config = new CsvHelper.Configuration.Configuration();
             using (var csv = new CsvWriter(writer, config))
             {
                 Assert.AreSame(config, csv.Configuration);
             }
         }
 }
Exemple #26
0
 public void EnsureInternalsAreSetupWhenPassingReaderAndConfigTest()
 {
     using (var stream = new MemoryStream())
         using (var reader = new StreamReader(stream))
         {
             var config = new CsvHelper.Configuration.Configuration();
             using (var parser = new CsvParser(reader, config))
             {
                 Assert.AreSame(config, parser.Configuration);
             }
         }
 }
Exemple #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleCsvDataReader" /> class.
        /// </summary>
        /// <param name="sourceFiles">The source files.</param>
        /// <param name="config">The configuration.</param>
        /// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
        public MultipleCsvDataReader(IEnumerable <ISourceFile> sourceFiles, Csv.Configuration config)
        {
            if (sourceFiles == null)
            {
                throw new ArgumentNullException("sourceFiles");
            }

            this.sourceFiles = new Queue <ISourceFile>(sourceFiles);
            this.config      = config ?? throw new ArgumentNullException("config");

            this.NextResultImpl();
        }
Exemple #28
0
        public void AutoMapWithNestedHeaders()
        {
            var config = new CsvHelper.Configuration.Configuration
            {
                PrefixReferenceHeaders = true,
            };
            var map = config.AutoMap <Nested>();

            Assert.AreEqual("Simple1.Id", map.ReferenceMaps[0].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Simple1.Name", map.ReferenceMaps[0].Data.Mapping.MemberMaps[1].Data.Names[0]);
            Assert.AreEqual("Simple2.Id", map.ReferenceMaps[1].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Simple2.Name", map.ReferenceMaps[1].Data.Mapping.MemberMaps[1].Data.Names[0]);
        }
Exemple #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CsvDataReader" /> class.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="sourceFile">The source file name to be embedded in the data stream.</param>
        /// <param name="config">The CSV configuration.</param>
        /// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
        public CsvDataReader(TextReader source, string sourceFile, Csv.Configuration config)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile));
            }

            DittoEventSource.Log.LoadingFile(sourceFile);
            this.sourceFile    = sourceFile;
            this.configuration = config ?? throw new ArgumentNullException(nameof(config));

            this.reader = new CsvReader(source, config);

            var lastWriteTime = File.GetLastWriteTimeUtc(this.sourceFile);

            // NB: I have made a choice here to prefix internal columns with underscores because
            // I have no idea what the real column names could be. The _prefix is consistent with
            // the old C++ compiler implementation style.
            this.fixedFields.Add(Tuple.Create <string, Func <object> >("_LineNumber", () => this.currentRow + 1));
            this.fixedFields.Add(Tuple.Create <string, Func <object> >("_SourceFile", () => this.sourceFile));
            this.fixedFields.Add(Tuple.Create <string, Func <object> >("_LastWriteTimeUtc", () => lastWriteTime));

            // Many reader functions throw exceptions until the first record has been read.
            this.closed = !this.reader.Read();

            if (this.configuration.HasHeaderRecord)
            {
                this.reader.ReadHeader();

                this.normalizedHeaders =
                    this.reader.Context.HeaderRecord
                    .Select(h => this.NormalizeFieldHeader(h))
                    .ToArray();

                this.closed = !this.reader.Read();
            }
            else
            {
                this.normalizedHeaders =
                    Enumerable.Range(1, this.reader.Context.Record.Length)
                    .Select(x => "Column" + x.ToString("G", CultureInfo.CurrentCulture))
                    .ToArray();
            }
        }
        public void EnsureReaderAndParserConfigIsAreSameTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                {
                    var csvReader = new CsvReader(reader);

                    Assert.AreSame(csvReader.Configuration, csvReader.Parser.Configuration);

                    var config = new CsvHelper.Configuration.Configuration();
                    var parser = new CsvParser(reader, config);
                    csvReader = new CsvReader(parser);

                    Assert.AreSame(csvReader.Configuration, csvReader.Parser.Configuration);
                }
        }