The official Fatica Labs Blog! RSS 2.0
# Saturday, April 17, 2010

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.

Saturday, April 17, 2010 9:02:23 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
log4net | Programmin

# Friday, April 16, 2010

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:

blog

 

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.

Friday, April 16, 2010 8:40:41 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
DasBlog

# Tuesday, March 30, 2010

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

s1

Ctrl+Space completion 2: Entity names

s2

Dot completion: property completion

 

s3

 

Ctrl+Space completion: all keywords and functions

 

s4

Here you can find the related sourceforge project.

Tuesday, March 30, 2010 4:44:42 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
HQL Intellisense | NHibernate

# Friday, February 26, 2010

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.

Friday, February 26, 2010 3:48:49 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback


# Sunday, December 13, 2009

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:

s1

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:

s2

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:

s3

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:

s4

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.

Sunday, December 13, 2009 3:38:22 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] - Trackback


# Saturday, October 17, 2009

Esiste, o meglio esisteva un tool di code generation, per creare automaticamente le classi partendo dai file di mapping di NHibernate. Questo tool (hbm2net, presente in NHContrib ) è stato un po' dimenticato, per cui ho deciso di provare a riesumarlo, e di ammodernarlo un po' dandogli la possibilità di utilizzare il Text Template Transformation Toolkit (T4). Ho previsto un template interno per la semplice generazione delle classi di mapping, ma potenzialmente è possibile generare con facilità qualsiasi altro codice provvedendo un template esterno, ad esempio mascherine di UI, layer WCF etc etc.

La versione attuale è una pre-alfa, serve solo a dare un'idea, e a vedere se ci sono delle dipendenze in deploy di difficile gestione, non è ben chiaro a me se T4 sia presente  in tutte le installazioni di Visual Studio.

Se volete provare il tool  potete scaricarlo da qui. Per utilizzare il templating T4 dovete utilizzare la seguente linea di comand:

hbm2net --config=t4config.xml *.hbm.xml

è importante utilizzare il config indicato, altrimenti hbm2net defaulta sul render di NVelocity.  Verra creata una cartella generated con i file sorgenti corrisondenti agli hbm.

Potete scaricare hbm2net da qui.

Per provare al volo è incluso nello zip anche un file di mapping simple1.hbm.xml.

Fatemi avere dei feedback!

 

Saturday, October 17, 2009 3:50:00 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] - Trackback
NHibernate

My Stack Overflow
Contacts

Send mail to the author(s) E-mail

Tags
profile for Felice Pollano at Stack Overflow, Q&A for professional and enthusiast programmers
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Felice Pollano
Sign In
Statistics
Total Posts: 143
This Year: 3
This Month: 0
This Week: 0
Comments: 105
This blog visits
All Content © 2012, Felice Pollano
DasBlog theme 'Business' created by Christoph De Baene (delarou) and modified by Felice Pollano