Fabio Maulo sta proponendo una nuova astrategia di mapping per NHibernate: ConfORM. In pratica si tratta di una strategia code only, quindi nessun file di XML, ma tutto via codice con l’approccio fluent interface. Stranamente la community si è un po’ stupita di vedere un ennesima strategia, e tutti stanno lì a chiedersi il perchè. Bene, il perchè è che è una nuova possibilità di scelta, ed avere molte scelte è un plus degli ambienti open source. In un suo post Fabio disegna uno scenario completo della ricca rosa di partecipanti al problema mapping. Difatto ConfORM è l’unica API che sfonda completamente lo strato hbm, e va direttamente alla radice. Tutto questo si traduce immediatamente in un incremento di performance, ed in una migliore linearità progettuale: meno strati è meglio, anzi, meno strati inutili è meglio. Francamente, dopo una piccola esperienza acquisita nel problema mapping con la scrittura del tool NHModeller, ho deciso di tornare ed imparare la strategia HBM. Dopo un po’ non è così male, ma la prossima volta che faccio un progetto mio provo ad usarlo ( in azienda non se ne parla nemmeno: già il mapping XML è visto come una stregoneria, e c’è chi legifera che mappare le foreign Key come long sia una buona idea anzichè un antipattern ). In conclusione: chissenefrega se un nuovo sistema sembra essere il duplicato di un altro:Vincerà il migliore, ed in ogni caso il migliore secondo gli utilizzatori 
Uno scenario di possibile utilizzo di RemotingAppender è quando si voglia concentrare in un unico punto i log di più app domain hostati nello stesso processo. Infatti un app domain separato vede difatto un’altra configurazione di log4net e, se si volesse per esempio usare un appender su file, ci sarebbe una violazione di condivisione. Per cui RemotingAppender torna utile, consentendo di ribaltare il log di tutti gli app domain sul programma principale. Per prima cosa bisogna mettere il programma principale in grado di ricevere le chiamate di log via remoting. Supponiamo che MyLauncher sia la classe che avvia un processo in un AppDomain separato, potremmo scrivere: class MyLauncher:MarshalByRefObject,log4net.Appender.RemotingAppender.IRemoteLoggingSink
{
E’ necessario che la classe derivi da MarshalByRef object, in quanto ne esporremo l’istanza via remoting. Deve altresì implementare IRemoteLoggingSink , per fungere da target per i messaggi di log4net.
A questo punto bisogna registrare il canale e l’istanza dell’oggetto atto a fare il sink dei messaggi:
1: private void PrepareRemotingLoggerListener() 2: { 3: var channel = new IpcChannel("log4net"+Guid.NewGuid().ToString()); 4: 5: ChannelServices.RegisterChannel(channel, false); 6: var oref = RemotingServices.Marshal(this, null); 7: AppenderURI = channel.GetUrlsForUri(oref.URI)[0]; 8: }
Supponiamo di chiamare il codice di sopra per ogni hosting di app domain. Il canale viene battezzato con una componente casuale, in modo da non entrare in conflitto con altre istanze dello stesso programma, o all’interno del medesimo processo se vi fossero più app domain esterni in esecuzione. Per registrare con remoting un istanza già creata si è usato RemotingServices.Marshal(---). Il codice memorizza in una proprietà AppenderURI: questo sarà l’indirizzo da usarsi con remoting appender per definire la proprietà Sink.In pratica è l’indirizzo remoting dell’oggetto “sink” dei messaggi.
Implementare IRemoteLoggingSink è facilissimo:
1: #region IRemoteLoggingSink Members 2: 3: public void LogEvents(log4net.Core.LoggingEvent[] events) 4: { 5: foreach (var le in events) 6: logger.Logger.Log(le); // logger è un'istanza di //ILog nel programma principale, ottenuta con logManager.GetLogger... 7: } 8: 9: #endregion
In questo modo si ottiene un redirect di tutti i messaggi sul logger dell’applicazione principale, con filtri e appender come stabilito dalla configurazione dell’applicativo principale. I messaggi saranno accodati, quindi non ci saranno violazioni di condivisione anche con appender su file fisico.
Nell’app domain basterà configurare log4net in modo da utilizzare RemotingAppender. Il modo più facile è utilizzare BasicConfigurator:
1: BasicConfigurator.Configure(CreateAppender()); 2: logger = LogManager.GetLogger("logger name");
CreateAppender si occuperà di creare il RemotingAppender in questo modo:
1: private IAppender CreateAppender() 2: { 3: RemotingAppender ra = new RemotingAppender(); 4: ra.Layout = new log4net.Layout.SimpleLayout(); 5: ra.Sink = LoggerURI; // Indirizzo del "sink" 6: ra.BufferSize = 512; 7: ra.Lossy = false; 8: ra.ActivateOptions(); // Ricordarsi di chiamare !!! 9: return ra; 10: }
Ed il gioco è fatto. LoggerUri è l’indirizzo dell’oggetto di sink ( vedi AppenderURI di prima ). BufferSize è il numero di messaggi da accodare prima di fare effettivamente la chiamata al canale: per ragioni di performance è meglio non abbassare troppo la soglia dei messaggi da raggruppare.
Finalmente, dopo tre anni passati con BlogEngine.NET, ho trovato il tempo di ritornare al fido DasBlog, secondo me il miglior blog engine con backend XML esistente. Ovviamente la causa del primo abbandono non era l’insoddisfazione, ma il fatto che Aruba, senza dire niente a nessuno, cambiasse da un momento all’altro le impostazioni del runtime .NET da full trust a medium trust. Per una serie di motivi DasBlog non era compatibile con tale modello, ma lo è stato in breve tempo. Nel contempo c’era blog engine .NET, che funzionava in medium trust, ma era povero e pieno di bachi. Dopo tre anni i bachi sono sempre gli stessi, per cui… meglio lasciare perdere. Per fare funzionare DasBlog su Aruba medium trust, tuttavia, bisogna dare qualche martellatina qua e la, perchè bisogna adattarsi alle meravigliose permission che hanno studiato i geniali sistemisti di Aruba, gli inventori di mdb-database, che nell’anno 2010 ci danno la gioia di usare un database access come nell’età della pietra… :) Bene, come dicevo, con qualche martellatina ai sorgenti, si ottiene facilmente questo: Tutto funzionante in medium trust, con le immagini che si inseriscono nella public, e i setting nella App-Data. Suggerisco di scaricare Windows Live Writer e attivate il nuovo account: Das Blog supporta il protocollo “Really Simple Discovery”, così collegarsi con live writer è un gioco da ragazzi, basta scegliere “altro blog engine”, inserire l’indirizzo del blog e la password, e fa tutto in automatico. Ovviamente se volete evitare di fare voi stessi le modifiche ai sorgenti di dasblog, potete scaricare la mia partch da qui. Prima di copiare i file su Aruba, modificate il file site.config in app_data, in modo che il tag <root> punti alla directory del vostro blog ( nel mio caso http://www.felicepollano.com ), e già che ci siete, mettete anche uno user e password furbi per l’amministratore editando sitesecurity.config. fatto questo copiate pure i file via FTP, o con altri potenti mezzi che Aruba mette a disposizione, scegliete il tema, e avete finito. E se… invece avete anche voi un altro engine in pista, e volete portare i vostri vecchi post su DasBlog ? Bene, io ho fatto così: Visto che il mio vecchio engine, bene o male, supportava le MetaWebLogAPI, ho scritto un piccolo tool command line per pompare i vecchi post sul nuovo motore. Ovviamente il nuovo motore l’ho installato momentaneamente in localhost, altrimenti come facevo ? ;) Il tool è assolutamente non user friendly, quindi se non avete voglia di dover mettere becco nei sorgenti lasciate pure perdere. In aggiunta, il tool usa una versione patchata della libreria metaweblog API di Pluralsight. La patch consiste nell’implementazione della funzione newMediaObject, non presente nella versione originale.
If anybody still uses HQL with NHibernate, it would probably find useful some editing with intellisense. Using the SharpDevelop Text Editor, the ANTLR grammar from the NHibernate sources, and some hacking in the java Eclipse Plugin code, the results is this: Ctrl+Space completion 1: entity alias Ctrl+Space completion 2: Entity names Dot completion: property completion Ctrl+Space completion: all keywords and functions  Here you can find the related sourceforge project.
Here you can find a reverse engineering tool, and a documentation on how to use it. At present only MSSQL is fully supported, but should be easy to provide strategies for other DB. The project is open source and can be found here in the trunk.This tool does not generate classes, to do so you can use hbm2net. The generated files are a good starting point if you have to start with NHibernate and legacy DBs.
You can download from here a new version of the hbm2net T4 enabled. This version has a better command line parsing/error handling, and the configuration file to provide ( optionally ) is validate in order to report some meaningful error messages when needed. The utility is still command line, I suggest to use as a pre-build step in Visual Studio to generate your entities, or other code artifacts you need. Unzip the files in a folder, and launch hbm2net: As you can see, the configuration file is now optional. If omitted, the default internal template is used, that will generate the code artifacts for the entities. You can specify an output directory for the files ( if omitted will be the current directory ) and a flag, –ct, to avoid generating files if target files are newer than sources. This is to suppress the reload message box in Visual Studio every time you compile if you forget an entity file opened. Then you can specify hbm files, with wildcards too. So, the simplest command line to generate mappings is:  If you want to use more generation step, you need to edit the configuration file, and inform hbm2net: hbm2net –config:myconfig.xml *.hbm.xml the configuration file is in the following format: The generator nodes can be multiple: each different generator can point to a different template in order to produce different code artifacts.The second parameter, output, is the file name you will generate. This is parsed internally by the T4 engine itself, so you can play your strategy in combining the file name having the clazz object, an instance of ClassMapping representing the current hbm fragment. The presented parameter produces a file called <classname>.generated.cs, and is the default behavior. Please note the template is specified as res://xxxx: this means to lookup the template internally. You can specify a template with a regular path as well, plus, you can use ~/xxx/yyy/mytemplate.tt to specify a path relative to the location where hbm2net is. A copy of hbm2net.tt is included in the zip however, so you can use as a starting point to create your generators. Some notes about T4. You will find the entire bible on that argument by starting here or here. I will show a snapshot of the hbm2net.tt of the current version: So, as you can see, very similar to the old asp stuff, not so different from NVelocity. The basic difference from other such engine is that we have reachable from inside the template any .NET type we can need. Furthermore, we can organize our generation with helpers by using the <#+ #> tags. Whit these tags we create a method inside the transformation class usable by the template itself. As an example, the <#=GetCommentForClass(clazz,1).TrimEnd()#> line call an helper function. In this case the body of this function is contained in the res://NHibernate.Tool.hbm2net.templates.common.tt file, but can be inlined with the template itself. Currently an object of type ClassMapping ( an internal hbm2net object used to represent a mapping fragment ) is passed to the template, as the field clazz. Sorry for the strange naming convention, I left something from the old original version, this maybe will change in future drops.
|