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 ^^

Wednesday, November 30, 2011

MVC Asp.Net controllers on multiple assemblies

Today I wrote some sort of "plug-in" for an ASP.NET MVC web application.
It was simply a controller with few action methods.
I really like the idea of separate the controller on a new assembly because it was some sort of "one-shot-use" controller, and soon will death.

But an unexpected problem pop-up at runtime: the MVC controller factory was unable to create the controller: "The IControllerFactory 'MyControllerFactory'did not return a controller for the name 'MyController'".
Looking on the web I wont be able to find any solution for my case.

Finally I dig deep into the MVC source (Asp.NET MVC is realesed as open-source) and I finally find the trick. When started, the controller factory, scan all classes seeking for controllers on all *loaded* assemblies: so to make it works, you have to load the assembly before the controller factory starts the scan.
You can do it as you like: my solution was to use a module that dynamically load ninject kernel modules.

Don't forget to write the right name for the controller: it must end with "Controller" ;-) .

Happy coding ^^

Saturday, November 26, 2011

NHibernate MappingByCode ManyToMany

I was not able to find a "loquacious" conformist example about a many-to-many relation mapping, so after play a bit with it, I finally deal with it.
Here an example:

 Bag(x => x.ManyToManyCollection
   , map =>
        map.Key(k => k.Column("child_key_column"));
   , action => action.ManyToMany(m => m.Column("parent_key_column")));

Happy mapping! ^^

Tuesday, November 22, 2011

Giornata Open Source Scuola Media Bernardino Di Betto‎ di Perugia

Segnalo questo evento aperto a tutti riguardante il progetto di adozione di sistemi GNU/Linux da parte di una scuola media Bernardino Di Betto‎ di Perugia.
Link dell'evento sul sito del GNU Linux User Group di Perugia.

Monday, November 21, 2011

Log4net: exclude a logger

Today I face the debugging need of exclude some noisy loggers: the logging library I'm using is log4net, now with new active volunteer developers and a new fresh release, the 1.2.11 published in 2011/10/12 .

To successfully silence a logger is quite simple: just use a filter, select the logger and quite it.

<filter type="log4net.Filter.LoggerMatchFilter">
   <loggerToMatch value="Logger.To.Exclude" />
   <acceptOnMatch value="false" />

This is the way to black-list a logger or a namespace.

Warning: filters elements may only be defined as children of <appender> elements.

Click here for the configuration manual.

This one is a very good article about filters in log4net.

Happy logging! :)

Saturday, November 19, 2011

.NET DateTime.ToString Patterns

Ho many time have you seek for a special Date/Time format string ?
Here is a very good table with all format :)

Friday, November 18, 2011

Privacy e sicurezza: evento gratuito formativo

Rigiro con piacere un invito ad un evento gratuito che si terrò il 14 dicembre 2011, alle ore 9.30 presso l'hotel Giò di Perugia.

Argomenti trattati:
  • Adempimenti 2011-2012, aggiornamenti normativi e recenti disposizioni
  • “Stato dell’arte” nelle PMI, a che punto siamo? Qual è il livello di attenzione?
  • Solo sanzioni? Quando la violazione della privacy configura altre ipotesi di reato.
  • “Oltre la privacy”, le azioni a tutela della riservatezza dei dati in azienda e fuori

Verrà rilasciato un regolare attestato valido ai fini della normativa vigente in materia di Privacy.

Per iscrizioni, inviare mail o fax ai seguenti riferimenti:


Infine ecco il volantino dell'evento:

Wednesday, November 16, 2011

NHibernate.MappingException: Could not determine type for: MyClass, for columns: NHibernate.Mapping.Column(id)

If you are using conformist mapping-by-code introduced by NHibernate in the 3.2, and are facing this exception maybe you have another problem.
If you define a Bag map like this
Bag(x => x.CollectionProp
     , map =>
        map.Key(km => km.Column("col_id"));
        map.Cascade(Cascade.All | Cascade.DeleteOrphans);
for a one-to-many association, you will retrieve this (misleading) exception. To solve it you have to specific the action in a way like this:
Bag(x => x.CollectionProp
     , map =>
        map.Key(km => km.Column("col_id"));
        map.Cascade(Cascade.All | Cascade.DeleteOrphans);
     , action => action.OneToMany()
A post about it on stack overflow.

NHibernate loquacious mapping config

Edit 2012/01/21: added some overloads to retrieve assemblies metadata loaded. This can be useful in many way, my one is the ability to serialize NHibernate configuration, like explained here.

I just publish a very small project for who uses NHibernate: it allows to use the web.config or app.config of your application to set up what assemblies load for the mapping in the "conformist" way.
For who doesn't know it, NHibernate is probably the best ORM for .NET existing on the way: and it's open source.
Loquacius mapping is the new "mapping by code" way introduced in 3.2 that basically comes from Fabio Maulo’s ConfORM.
Here's the link of the project:

How to set up all:
  1. download and compile de project;
  2. add to your .config file a section to the configSection node like this:
       type="NHibernate.LoquaciousMappingConfig.Config.LoquaciousNHibernateMappingSection, NHibernate.LoquaciousMappingConfig"/>
  3. add the configuration containing the list of your assemblies:
             <add assembly="YourAssebly"/>
  4. call the extended method to read the configuration and load the assemblies:
    var cfg = new Configuration().Configure();
    // your other coded config stuff
    var mapper = new ModelMapper();
    mapper.AddFromConfig(); // here the lib extended method
    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
    cfg.AddDeserializedMapping(mapping, "yourDocumentName");
    var sessionFactory = cfg.BuildSessionFactory(); 
All done !

I found it very useful in my (quite big) project to use both FluentNHibernate and the mapping-by-code cause I would like to migrate all the maps to the loquacious one.
Simply add these lines of code after the cfg.AddDeserializadMapping(..)  and replace the SessionFactory build:

// reuse the same cfg object with the mapping by code just added
var sessionFactory = Fluently.Configure(cfg)
    .Mappings(x => x.FluentMappings.AddFromAssemblyOf<YourClass>() /* or the method you like */)

So you will have both fluent and loquacious mapping in your projects.

Happy coding! :)

Tuesday, November 15, 2011

Another IT blog...why?

I decided to start a blog some time ago, and I finally found the time to do it :)
Why? Well... I like the idea of sharing information and knowledge about my projects, programming, .net, java, open source projects, problems and so on...

The English language is the natural choice for an information technology blog.
So let's see what will happen :-)

Happy hunting ^^