Friday, December 16, 2011

.NET CSV open source read write library

Yesterday I was in the need of write a lot of data exports in CSV (comma separated values) format.
To write a CSV-writer by my self should not be a big deal, but, you know, to write, to test, to fix (and go on) a common problem, that for sure has been solved, is not too wise.
So I googled a bit and finally find a very good CSV library, CvsHelper, hosted on GitHub and written by Josh Close in C#.
CvsHelper is very well written, it have a NUnit test project and have a lot of features.
One of them I like a lot, is the possibility to write a CsvClassMap for your business class, with your map logic, in a way very similar to the ClassMap of FluentNHibernate or the loquacius mapping by code of NHibernate 3.2.
Here an example:

  public sealed class MyClassMap : CsvClassMap<MyClass>
  {
     public MyClassMap()
     {
        int i = -1;
        Map(a => a.Id).Index(++i).Name("Id");
        Map(a => a.MyProperty).Index(++i).Name("My Prop in CSV");
        Map(a => a.MyProperty2).Index(++i).Name("My Property 2");
     }
  }

There is also a way to do a map with attributes, but to be honest, I don't like it (I prefer to have classes more decoupled possible).

Another feature is the possibility to define and use a custom TypeConverter (example in the source file linked below).

Of course you can write any sort of custom csv file you like, the library will take care about the correct csv format.

Here there is an example with many possibility usage.

Happy coding! :-)

Monday, December 5, 2011

NullReferenceException on CompileMappingForAllExplicitlyAddedEntities ModelMapper for NHibernate 3.2

If you're using NHibernate 3.2, and when call the CompileMappingForAllExplicitlyAddedEntities() method of your ModelMapper object, you have to check none of your added classes are defined without a namespace.
This could happen if you are added all types defined in your assemblies (calling for example mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes() ), and at least one of your classes is compiled in the empty namespace ...
To solve this error, you have to define these classes in a namespace (it is always a good practice).

The error is caused by the NHibernate source code, because doesn't take care about empty namespaces.

The thread about that problem on nhuser google group.

Happy debugging ^^