public void AddGetRemoveTest()
        {
            var config        = new CsvHelper.Configuration.Configuration();
            var customOptions = new TypeConverterOptions
            {
                Formats = new string[] { "custom" },
            };

            config.TypeConverterOptionsCache.AddOptions <string>(customOptions);
            var options = config.TypeConverterOptionsCache.GetOptions <string>();

            Assert.AreEqual(customOptions.Formats, options.Formats);

            config.TypeConverterOptionsCache.RemoveOptions <string>();

            options = config.TypeConverterOptionsCache.GetOptions <string>();

            Assert.AreNotEqual(customOptions.Formats, options.Formats);
        }
Beispiel #2
0
        /// <inheritdoc/>
        public virtual void WriteField <T>(T field, ITypeConverter converter)
        {
            var type = field == null ? typeof(string) : field.GetType();

            reusableMemberMapData.TypeConverter = converter;
            if (!typeConverterOptionsCache.TryGetValue(type, out TypeConverterOptions typeConverterOptions))
            {
                typeConverterOptions = TypeConverterOptions.Merge(new TypeConverterOptions {
                    CultureInfo = cultureInfo
                }, context.TypeConverterOptionsCache.GetOptions(type));
                typeConverterOptionsCache.Add(type, typeConverterOptions);
            }

            reusableMemberMapData.TypeConverterOptions = typeConverterOptions;

            var fieldString = converter.ConvertToString(field, this, reusableMemberMapData);

            WriteConvertedField(fieldString, type);
        }
        public void GetRecordsTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csvReader = new CsvReader(reader))
                        {
                            writer.WriteLine("\"1,234\",\"5,678\"");
                            writer.Flush();
                            stream.Position = 0;

                            var options = new TypeConverterOptions {
                                NumberStyle = NumberStyles.AllowThousands
                            };
                            csvReader.Configuration.TypeConverterOptionsCache.AddOptions <int>(options);
                            csvReader.Configuration.HasHeaderRecord = false;
                            csvReader.GetRecords <Test>().ToList();
                        }
        }
Beispiel #4
0
        public void AddGetRemoveTest()
        {
            var customOptions = new TypeConverterOptions
            {
                Formats = new string[] { "custom" },
            };
            var typeConverterOptionsFactory = new TypeConverterOptionsCache();

            typeConverterOptionsFactory.AddOptions <string>(customOptions);
            var options = typeConverterOptionsFactory.GetOptions <string>();

            Assert.AreEqual(customOptions.Formats, options.Formats);

            typeConverterOptionsFactory.RemoveOptions <string>();

            options = typeConverterOptionsFactory.GetOptions <string>();

            Assert.AreNotEqual(customOptions.Formats, options.Formats);
        }
        public void ConvertFromStringTest()
        {
            var converter            = new BooleanConverter();
            var typeConverterOptions = new TypeConverterOptions
            {
                CultureInfo = CultureInfo.CurrentCulture
            };

            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "true"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "True"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "TRUE"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "1"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "yes"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "YES"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "y"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, "Y"));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, " true "));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, " yes "));
            Assert.IsTrue((bool)converter.ConvertFromString(typeConverterOptions, " y "));

            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "false"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "False"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "FALSE"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "0"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "no"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "NO"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "n"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, "N"));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, " false "));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, " 0 "));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, " no "));
            Assert.IsFalse((bool)converter.ConvertFromString(typeConverterOptions, " n "));

            try
            {
                converter.ConvertFromString(typeConverterOptions, null);
                Assert.Fail();
            }
            catch (CsvTypeConverterException)
            {
            }
        }
        public void WriteFieldTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csvWriter = new CsvWriter(writer))
                        {
                            var options = new TypeConverterOptions {
                                Format = "c"
                            };
                            csvWriter.Configuration.TypeConverterOptionsFactory.AddOptions <int>(options);
                            csvWriter.WriteField(1234);
                            csvWriter.NextRecord();
                            writer.Flush();
                            stream.Position = 0;
                            var record = reader.ReadToEnd();

                            Assert.AreEqual("\"$1,234.00\"\r\n", record);
                        }
        }
Beispiel #7
0
    public byte[] GetTemplate <T, TMap>(string delimiter = ";", string newLine = "\n", bool hasHeaderRecord = false) where TMap : ClassMap <T> where T : class, new()
    {
        using var fileStream = new MemoryStream();
        using var writer     = new StreamWriter(fileStream);
        using var csv        = new CsvWriter(writer, GetBaseConfiguration(delimiter, newLine, hasHeaderRecord));
        var options = new TypeConverterOptions {
            Formats = new[] { "yyyy-MM-ddTHH:mm:ss:fff" }
        };

        csv.Context.TypeConverterOptionsCache.AddOptions <DateTime>(options);
        csv.Context.TypeConverterOptionsCache.AddOptions <DateTime?>(options);
        csv.Context.RegisterClassMap <TMap>();
        csv.WriteHeader <T>();
        csv.NextRecord();
        csv.WriteRecords(new List <T>()
        {
        });
        csv.Flush();
        return(fileStream.ToArray());
    }
Beispiel #8
0
        public void ConvertFromStringTest()
        {
            var converter            = new CharConverter();
            var typeConverterOptions = new TypeConverterOptions
            {
                CultureInfo = CultureInfo.CurrentCulture
            };

            Assert.AreEqual('a', converter.ConvertFromString(typeConverterOptions, "a"));
            Assert.AreEqual('a', converter.ConvertFromString(typeConverterOptions, " a "));

            try
            {
                converter.ConvertFromString(typeConverterOptions, null);
                Assert.Fail();
            }
            catch (CsvTypeConverterException)
            {
            }
        }
        public void AddGetRemoveTest()
        {
            var config        = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var context       = new CsvContext(config);
            var customOptions = new TypeConverterOptions
            {
                Formats = new string[] { "custom" },
            };

            context.TypeConverterOptionsCache.AddOptions <string>(customOptions);
            var options = context.TypeConverterOptionsCache.GetOptions <string>();

            Assert.Equal(customOptions.Formats, options.Formats);

            context.TypeConverterOptionsCache.RemoveOptions <string>();

            options = context.TypeConverterOptionsCache.GetOptions <string>();

            Assert.NotEqual(customOptions.Formats, options.Formats);
        }
		public void GetRecordsAppliedWhenMappedTest()
		{
			var options = new TypeConverterOptions { NumberStyle = NumberStyles.AllowThousands };

			using (var stream = new MemoryStream())
			using (var reader = new StreamReader(stream))
			using (var writer = new StreamWriter(stream))
			using (var csvReader = new CsvReader(reader))
			{
				csvReader.Configuration.Delimiter = ",";
				writer.WriteLine("\"1,234\",\"$5,678\"");
				writer.Flush();
				stream.Position = 0;

				csvReader.Configuration.TypeConverterOptionsCache.AddOptions<int>(options);
				csvReader.Configuration.HasHeaderRecord = false;
				csvReader.Configuration.RegisterClassMap<TestMap>();
				csvReader.GetRecords<Test>().ToList();
			}
		}
Beispiel #11
0
        public override object ConvertFromString(TypeConverterOptions options, string text)
        {
            string[]       vals     = text.Split(' ');
            List <Orbital> orbitals = new List <Orbital>();
            string         basedOn  = "";

            foreach (var val in vals)
            {
                if (val.StartsWith("["))
                {
                    basedOn = val.Substring(1, val.Length - 2);
                    continue;
                }
                var shell = byte.Parse(val.Substring(0, 1));
                var type  = char.Parse(val.Substring(1, 1));
                var count = byte.Parse(val.Substring(2));
                orbitals.Add(new Orbital(shell, type, count));
            }
            return(new Configuration(basedOn, orbitals.ToArray()));
        }
        public IEnumerable <Transaction> Parse(IFormFile file)
        {
            var stream = file.OpenReadStream();

            using var reader = new StreamReader(stream);
            using var csv    = new CsvReader(reader, CultureInfo.InvariantCulture);

            var options = new TypeConverterOptions
            {
                Formats = new [] { "dd/MM/yyyy hh:mm:ss" }
            };

            csv.Configuration.TypeConverterOptionsCache.AddOptions <DateTime>(options);
            csv.Configuration.HasHeaderRecord = false;
            csv.Configuration.TrimOptions     = TrimOptions.Trim;

            var records = csv.GetRecords <Transaction>();

            return(records.ToList());
        }
        protected override object ConvertFrom(TypeConverterOptions options, string text)
        {
            DateTime time;

            if (text.EqualIgnoreCase("unknown"))
            {
                return(DateTime.MinValue);
            }
            if (!DateTime.TryParse(text, out time))
            {
                return(DateTime.MinValue);
            }

            /*if (!DateTime.TryParseExact(text, "g", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None,
             *  out time))
             * {
             *  return DateTime.MinValue;
             * }*/
            return(time);
        }
Beispiel #14
0
        public void ProcessFile(string filename)
        {
            DataList.Clear();

            using var fileReader = File.OpenText(filename);
            var csv = new CsvReader(fileReader, CultureInfo.InvariantCulture);


            var o = new TypeConverterOptions
            {
                DateTimeStyle = DateTimeStyles.AssumeUniversal & DateTimeStyles.AdjustToUniversal
            };

            csv.Context.TypeConverterOptionsCache.AddOptions <KapeCopyLogData>(o);


            var foo = csv.Context.AutoMap <KapeCopyLogData>();

            foo.Map(t => t.Line).Ignore();
            foo.Map(t => t.Tag).Ignore();

            csv.Context.RegisterClassMap(foo);



            var records = csv.GetRecords <KapeCopyLogData>();

            var ln = 1;

            foreach (var record in records)
            {
                Log.Debug("Line # {Line}, Record: {RawRecord}", ln, csv.Context.Parser.RawRecord);
                record.Line = ln;

                record.Tag = TaggedLines.Contains(ln);

                DataList.Add(record);

                ln += 1;
            }
        }
Beispiel #15
0
        private static async Task <LocationInfo> GetInfo(TraceWriter log, BeaconData beacon, ExecutionContext context)
        {
            LogHelper.Log(log, $"GetBeaconIdentifier called: {beacon.Identifier}");

            if (string.IsNullOrEmpty(beacon.Identifier))
            {
                return(null);
            }
            var path = $"{context.FunctionAppDirectory}\\beacons.csv";

            using (TextReader reader = File.OpenText(path))
            {
                var configuration = new Configuration {
                    HasHeaderRecord = true,
                };

                var doubleConverterOptions = new TypeConverterOptions {
                    CultureInfo = CultureInfo.InvariantCulture
                };

                var csv = new CsvReader(reader, configuration);
                csv.Configuration.TypeConverterOptionsCache.AddOptions <double>(doubleConverterOptions);

                await csv.ReadAsync(); // skip first header line

                while (await csv.ReadAsync())
                {
                    var name = csv.GetField <string>(0);
                    if (!string.IsNullOrEmpty(name) && name.Equals(beacon.Identifier, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(new LocationInfo
                        {
                            Name = csv.GetField <string>(1),
                            Coordinates = new GeoCoordinates(csv.GetField <double>(4), csv.GetField <double>(5)),
                            Beacon = beacon
                        });
                    }
                }
            }
            return(null);
        }
Beispiel #16
0
        /// <summary>
        /// Creates a <see cref="Delegate"/> of type <see cref="Func{T}"/>
        /// that will create a record of the given type using the current
        /// reader row.
        /// </summary>
        /// <param name="recordType">The record type.</param>
        protected override Delegate CreateCreateRecordDelegate(Type recordType)
        {
            var        method          = typeof(IReaderRow).GetProperty("Item", typeof(string), new[] { typeof(int) }).GetGetMethod();
            Expression fieldExpression = Expression.Call(Expression.Constant(Reader), method, Expression.Constant(0, typeof(int)));

            var memberMapData = new MemberMapData(null)
            {
                Index         = 0,
                TypeConverter = Reader.Configuration.TypeConverterFactory.GetConverter(recordType)
            };

            memberMapData.TypeConverterOptions             = TypeConverterOptions.Merge(new TypeConverterOptions(), Reader.context.ReaderConfiguration.TypeConverterOptionsFactory.GetOptions(recordType));
            memberMapData.TypeConverterOptions.CultureInfo = Reader.context.ReaderConfiguration.CultureInfo;

            fieldExpression = Expression.Call(Expression.Constant(memberMapData.TypeConverter), "ConvertFromString", null, fieldExpression, Expression.Constant(Reader), Expression.Constant(memberMapData));
            fieldExpression = Expression.Convert(fieldExpression, recordType);

            var funcType = typeof(Func <>).MakeGenericType(recordType);

            return(Expression.Lambda(funcType, fieldExpression).Compile());
        }
Beispiel #17
0
        public override string ConvertToString(TypeConverterOptions options, object value)
        {
            var list = (List <BoxTrackingCode>)value;

            if (list == null)
            {
                list = new List <BoxTrackingCode>();
            }
            var trackingCodeStrings = new StringBuilder();

            for (var i = 0; i < list.Count; i++)
            {
                var trackingCode = list[i];
                trackingCodeStrings.Append($"name:{trackingCode.Name},value:{trackingCode.Value}");
                if (i != list.Count - 1)
                {
                    trackingCodeStrings.Append(Environment.NewLine);
                }
            }
            return(trackingCodeStrings.ToString());
        }
        public object ConvertFromString(TypeConverterOptions options, string text)
        {
            DateTime result;

            if (text.Contains("/") && DateTime.TryParse(text, new CultureInfo("en-US"), DateTimeStyles.None, out result))
            {
                return(result);
            }

            if (DateTime.TryParse(text, new CultureInfo("de-DE"), DateTimeStyles.None, out result))
            {
                return(result);
            }

            if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
            {
                return(result);
            }

            throw new Exception("Unable to parse date '" + text + "'.");
        }
        public void WriteFieldTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csvWriter = new CsvWriter(writer, new CultureInfo("en-US")))
                        {
                            csvWriter.Configuration.Delimiter = ",";
                            var options = new TypeConverterOptions {
                                Formats = new string[] { "c" }
                            };
                            csvWriter.Configuration.TypeConverterOptionsCache.AddOptions <int>(options);
                            csvWriter.WriteField(1234);
                            csvWriter.NextRecord();
                            writer.Flush();
                            stream.Position = 0;
                            var record = reader.ReadToEnd();

                            Assert.AreEqual("\"$1,234.00\"\r\n", record);
                        }
        }
Beispiel #20
0
        private static List <Movie> GetMovies(string fileName)
        {
            List <Movie> returnValue = new List <Movie>();

            if (File.Exists(fileName))
            {
                using (var reader = new StreamReader(fileName))
                {
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        csv.Configuration.Delimiter = ",";
                        var options = new TypeConverterOptions {
                            Formats = new[] { "yyyy-MM-dd" }
                        };
                        csv.Configuration.TypeConverterOptionsCache.AddOptions <DateTime>(options);
                        returnValue = csv.GetRecords <Movie>().ToList();
                    }
                }
            }
            return(returnValue);
        }
        public override string ConvertToString(TypeConverterOptions options, object value)
        {
            var location = value as CsvJobLocation;

            if (location == null)
            {
                return(string.Empty);
            }

            var result =
                // ReSharper disable once UseStringInterpolation
                string.Format("{0} {1} {2} {3} {4} {5}",
                              location.Street,
                              location.HouseNumber,
                              string.IsNullOrEmpty(location.FloorLevel) ? string.Empty : "(Stockwerk: " + location.FloorLevel + ")",
                              location.ZipCode,
                              location.City,
                              string.IsNullOrEmpty(location.AdditionalDescription) ? string.Empty : "Zusatzbeschreibung: " + location.AdditionalDescription);

            return(result);
        }
Beispiel #22
0
        public void ConvertFromExcelTest()
        {
            var converter            = new Int16Converter();
            var typeConverterOptions = new TypeConverterOptions {
                CultureInfo = CultureInfo.CurrentCulture
            };

            Assert.AreEqual((short)123, converter.ConvertFromExcel(typeConverterOptions, (double)123));
            Assert.AreEqual((short)123, converter.ConvertFromExcel(typeConverterOptions, "123"));
            Assert.AreEqual((short)123, converter.ConvertFromExcel(typeConverterOptions, " 123 "));
            Assert.AreEqual((short)0, converter.ConvertFromExcel(typeConverterOptions, null));

            typeConverterOptions.NumberStyle = NumberStyles.HexNumber;
            Assert.AreEqual((short)0x123, converter.ConvertFromExcel(typeConverterOptions, "123"));

            try {
                converter.ConvertFromExcel(typeConverterOptions, "");
                Assert.Fail();
            } catch (ExcelTypeConverterException) {
            }
        }
        public void GetFieldTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csvReader = new CsvReader(reader))
                        {
                            writer.WriteLine("\"1,234\",\"5,678\"");
                            writer.Flush();
                            stream.Position = 0;

                            var options = new TypeConverterOptions {
                                NumberStyle = NumberStyles.AllowThousands
                            };
                            csvReader.Configuration.TypeConverterOptionsFactory.AddOptions <int>(options);
                            csvReader.Configuration.HasHeaderRecord = false;
                            csvReader.Read();
                            Assert.AreEqual(1234, csvReader.GetField <int>(0));
                            Assert.AreEqual(5678, csvReader.GetField(typeof(int), 1));
                        }
        }
Beispiel #24
0
 private void btnDownload_Click(object sender, EventArgs e)
 {
     try
     {
         if (string.IsNullOrEmpty(_selectedCsvFileName))
         {
             MessageBox.Show("Please select file");
             return;
         }
         var button = (Button)sender;
         button.Visible = false;
         ClearTextInput();
         SetLoading(true);
         var fileName = $"{Guid.NewGuid()}.csv";
         using var fileStream   = File.Create(fileName);
         using var streamReader = new StreamReader(_selectedCsvFileName);
         using var streamWriter = new StreamWriter(fileStream)
               {
                   AutoFlush = true
               };
         using var csvWriter = new CsvWriter(streamWriter);
         using var csvReader = new CsvReader(streamReader);
         var options = new TypeConverterOptions {
             Formats = new[] { "MM/dd/yyyy hh:mm" }
         };
         csvWriter.Configuration.TypeConverterOptionsCache.AddOptions <DateTime>(options);
         WriteHeader(csvWriter);
         WriteContents(csvReader, csvWriter);
         SetLoading(false);
         OpenCreatedFile(fileName);
         _selectedCsvFileName = string.Empty;
         button.Visible       = true;
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
         SetLoading(false);
         ClearTextInput();
     }
 }
Beispiel #25
0
        public object ConvertFromString(TypeConverterOptions options, string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(null);
            }

            var items = text.Split(
                new[] { InnerFieldDelimiter, InnerItemDelimiter },
                StringSplitOptions.RemoveEmptyEntries);

            var result = new HashSet <Point>();

            for (int i = 0; i < items.Length; i += 2)
            {
                var a = int.Parse(items[i], options.NumberStyle.GetValueOrDefault());
                var b = int.Parse(items[i + 1], options.NumberStyle.GetValueOrDefault());
                result.Add(new Point(a, b));
            }

            return(result);
        }
        public void ConvertFromExcelTest()
        {
            var converter            = new EnumConverter(typeof(TestEnum));
            var typeConverterOptions = new TypeConverterOptions {
                CultureInfo = CultureInfo.CurrentCulture
            };

            Assert.AreEqual(TestEnum.One, converter.ConvertFromExcel(typeConverterOptions, "One"));
            Assert.AreEqual(TestEnum.One, converter.ConvertFromExcel(typeConverterOptions, "one"));
            Assert.AreEqual(TestEnum.One, converter.ConvertFromExcel(typeConverterOptions, "1"));
            try {
                Assert.AreEqual(TestEnum.One, converter.ConvertFromExcel(typeConverterOptions, ""));
                Assert.Fail();
            } catch (ExcelTypeConverterException) {
            }

            try {
                Assert.AreEqual(TestEnum.One, converter.ConvertFromExcel(typeConverterOptions, null));
                Assert.Fail();
            } catch (ExcelTypeConverterException) {
            }
        }
        /// <summary>
        /// Writes the field to the CSV file.
        /// When all fields are written for a record,
        /// <see cref="IWriter.NextRecord" /> must be called
        /// to complete writing of the current record.
        /// </summary>
        /// <typeparam name="T">The type of the field.</typeparam>
        /// <param name="field">The field to write.</param>
        /// <param name="converter">The converter used to convert the field into a string.</param>
        public virtual void WriteField <T>(T field, ITypeConverter converter)
        {
            var type = field == null ? typeof(string) : field.GetType();

            context.ReusableMemberMapData.TypeConverter = converter;
            //if( !context.TypeConverterOptionsCache.TryGetValue( type, out TypeConverterOptions typeConverterOptions ) )
            TypeConverterOptions typeConverterOptions = CSharp6Extension.TryGetValue <Type, TypeConverterOptions>(context.TypeConverterOptionsCache, type);

            if (typeConverterOptions == default(TypeConverterOptions))
            {
                typeConverterOptions = TypeConverterOptions.Merge(new TypeConverterOptions {
                    CultureInfo = context.WriterConfiguration.CultureInfo
                }, context.WriterConfiguration.TypeConverterOptionsCache.GetOptions(type));
                context.TypeConverterOptionsCache.Add(type, typeConverterOptions);
            }

            context.ReusableMemberMapData.TypeConverterOptions = typeConverterOptions;

            var fieldString = converter.ConvertToString(field, this, context.ReusableMemberMapData);

            WriteConvertedField(fieldString);
        }
        public override string ConvertToString(TypeConverterOptions options, object value)
        {
            var personsCollection = value as IEnumerable <CsvPerson>;
            var singlePerson      = value as CsvPerson;

            var result = string.Empty;

            // If the object is a list of persons, save full person list of persons
            if (personsCollection != null)
            {
                result = personsCollection.Aggregate(string.Empty, (current, person) => current +
                                                     $"({person.Prename} {person.Surname}) ");
            }

            // if it's just a single person, save this person
            if (singlePerson != null)
            {
                result = $"{singlePerson.Prename} {singlePerson.Surname}";
            }

            return(result);
        }
        public void ConvertFromExcelTest()
        {
            var converter            = new TimeSpanConverter();
            var typeConverterOptions = new TypeConverterOptions {
                CultureInfo = CultureInfo.CurrentCulture
            };

            var dateTime   = DateTime.Now;
            var timeSpan   = new TimeSpan(dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
            var timeString = timeSpan.ToString();

            // Valid conversions.
            Assert.AreEqual(timeString, converter.ConvertFromExcel(typeConverterOptions, timeSpan.ToString()).ToString());
            Assert.AreEqual(timeString, converter.ConvertFromExcel(typeConverterOptions, " " + timeSpan + " ").ToString());

            // Invalid conversions.
            try {
                converter.ConvertFromExcel(typeConverterOptions, null);
                Assert.Fail();
            } catch (ExcelTypeConverterException) {
            }
        }
Beispiel #30
0
        public void ComponentModelCompatibilityTest()
        {
            var converter   = new TimeSpanConverter();
            var cmConverter = new System.ComponentModel.TimeSpanConverter();

            var typeConverterOptions = new TypeConverterOptions
            {
                CultureInfo = CultureInfo.CurrentCulture
            };

            try
            {
                cmConverter.ConvertFromString("");
                Assert.Fail();
            }
            catch (FormatException) {}

            try
            {
                var val = (DateTime)converter.ConvertFromString(typeConverterOptions, "");
                Assert.Fail();
            }
            catch (CsvTypeConverterException) {}

            try
            {
                cmConverter.ConvertFromString(null);
                Assert.Fail();
            }
            catch (NotSupportedException) { }

            try
            {
                converter.ConvertFromString(typeConverterOptions, null);
                Assert.Fail();
            }
            catch (CsvTypeConverterException) { }
        }