Hi!

..as what I said in my previous post, I do my job (even if I consider it no just a Job) with passion and happyness, even if lately some things makes me crazy and over stress.. But, now I like to share with all some good readings which i read in these days and more…

The first one it’s the Software by Rob Blog, I found it reading another great Blog I read because of sharing of concept of Developing with passion, the Blod of Jean-Paul S. Boodhoo. I really like these blogs because of what they say about our work of, first, developers.. Since when I started learning programming in Basic, I took this experience as a passion, I could say I do many things with passion, cause I consider the passion a great piece of LIFE, and my Life.

In my Job I like to put everyday all of my intentions and passion to let became the job a good place, to permit my colleagues to learn and me to learn from them, and last to do the real job of writing code and design architectures with passion as if I made a paint or compose a baroque music with my guitar as John Dowland…I’m joking but this is the idea..

I really like the Rob’s Becoming a Better Developer series, because I share the conscepts Robs try to share with others, I rtealluy like his series, I found pieces of mine in every post so I suggest to learn it.

We (Developers who has a Blog and writes out some contents) live, I think, in a sort of great-fantastic dimension of working, coding, and anything you can thing related to our job.. because in my day by day job, I can see horrible things starting from what usual developers writes in their code.. recently I read a post from Andrea Boschin’s Blog, he writes about bad coding facts, this kind of things are everyday things in our job, I don’t know in what kind of world we imagine to live and work, but every day I see terrible things happen just because it’s needed to “do it fast and do it as cheeper as possible”…

Ciao!

Hi, as usual in these weeks I have no time to write anything, I’m sorry because I’ve in mind many things I like to share, produce and more, but my time is over!

Now, I’ come back from my vacations a 3 weeks ago, and my job is falling on me as in the middle of the year, I need absolutely to take some more time, but I wish to talk about some thoughts… I like to begin this new job year as better as possible, there are so many new tech areas to skill about, and new things to learn, I’m really excited to begin, nut I hope this process would be in a “regular” and under-stress form.

Now, better, Monday, I will be on the end of my current project, my first-total-java-project I ever made, and I have to say it was a good experience, I have to notice that what my great dad-teacher-mentor told me years ago it’s really a true fact, “..it cames a moment where a language would be similar to another one..” this because my mind has changed.  

I saw that my knowledge of c# and NHibernate first, then all my knowledge on development, was very important, I could made a near a total porting of my NHibernate knowledge to Java, and I saw the same on Spring and other things…

But the real thing really make me thinking was that my Java colleagues, didn’t know something, I could say, I teached to them.. It’s a long discussion, but this surprise me, and this is another piece in the puzzle that makes me realize better developing is a passion, a real passion, a passion to learn first and the to investigate, to find out better solutons, to find a compromise, to makes every time not just and hand-work, but a “mind-opera”..may be this could be exagerate as a sentence, but I like to think a doing my job with passion like an artist, this makes me doing my job with pleasure and happiness not just like a day-by-day job.

I hope who will read this post doesn’t just think it’s too long…

Ciao!

 

Now, after some “heavy” working-months I can go to my vacations!! This is just the FIRST PART, but one I love,  In the end I’m hoping I can stay one calm week on, yes “on” the sea in Tuscany, I’m so happy to go there, but as everytime happen, I will read a beautiful tech book, Windows Presentation Foundation Unleashed I hope, or maybe something about architecture. So Happy Holydays to everybody!

Ciao!

Technorati Tag:

Hi, I wish to start to post something about WCF, some useful content, someone could find my-blogged-practice trivial or something bad, but first I like to share contents, second this is my “little” way I found useful in my daily job.

This time I wish to talk about Factories, exactly the factory I use to instantiate WCF services in clients. First let me know I don’t really like VisualStudio generated proxies, I don’t like the concept behind a generated proxy like this, my problem began with ASMX generated proxies, and now is still alive with WCF proxies.

I like to have, or to possibly-have, control over intantiation of client proxyes and more, maybe services on server side, many situations I found I needed to have some kind of control on that, and I love WCF for all of the features and extensibility offered. Maybe could be necessary to inject policies, change behaviors, work with addressing, or even encapsulate the features normally written in configuration, this it’s possible with simple and little factory I merely named ServiceFactory.

Now, let begin with another concept, It’s clear that, if one can or would use a factory to create service clients, it’s clear that contracts are shared by a shared assembly, so it would be useful to have a generic ServiceFactory, this could be extended by other features, but focus on simplicity, the factory is quite simple:

First we start create the class defiition, now I will use the simplest static-methods one, but I don’t really like it, I prefer the Singleton kind:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.ServiceModel;
   6:  
   7: namespace XGuy.Common.Services
   8: {
   9:     /// <summary>
  10:     /// Represent the Factorym used to create service 
  11:     /// clients proxy transparently
  12:     /// </summary>
  13:     public class ServiceFactory
  14:     {

Next, there are essently 3 methods could be used to create proxy services:

   1: /// <summary>
   2: /// Create a new service proxy based on service 
   3: /// endpoint interface
   4: /// </summary>
   5: /// <typeparam name="T">
   6: /// the service-interface to use
   7: /// </typeparam>
   8: /// <returns>an interface transparent proxy</returns>
   9: public static T CreateClient<T>() where T : class
  10: {
  11:     Type contract = typeof(T);
  12:     return CreateClient<T>(contract.Name);
  13: }

This first method can be used direct on an inetrface type

   1: using System;
   2: using System.Collections;
   3: using XGuy.Common.Services;
   4:  
   5: namespace XGuy.Testbench
   6: {
   7:     class Program
   8:     {
   9:         public static void Main()
  10:         {
  11:             ITestService service = 
  12:                 ServiceFactory.CreateClient<ITestService>();
  13:             service.DoSomething();
  14:         }
  15:     }
  16: }

The second and third method can be used in the same manner, but woh named configured services:

   1: /// <summary>
   2: /// Create a new service proxy based on service 
   3: /// endpoint interface by name
   4: /// </summary>
   5: /// <typeparam name="T">the service-interface to use</typeparam>
   6: /// <param name="serviceName">
   7: /// the named configured service reference to use
   8: /// </param>
   9: /// <returns>an interface transparent proxy</returns>
  10: public static T CreateClient<T>(Enum serviceName) where T : class
  11: {
  12:     return CreateClient<T>(serviceName.ToString());
  13: }
  14:  
  15: /// <summary>
  16: /// Create a new service proxy based on service 
  17: /// endpoint interface by name
  18: /// </summary>
  19: /// <typeparam name="T">the service-interface to use</typeparam>
  20: /// <param name="serviceName">
  21: /// the named configured service reference to use
  22: /// </param>
  23: /// <returns>an interface transparent proxy</returns>
  24: public static T CreateClient<T>(string serviceName) where T : class
  25: {
  26:     //get the 'default' value based on type (this could be normally a null)
  27:     T result = default(T);
  28:     //obtain the 'real' interface type reference
  29:     Type contract = typeof(T);
  30:  
  31:     ChannelFactory<T> channelFactory = new ChannelFactory<T>(serviceName);
  32:     result = channelFactory.CreateChannel();
  33:     
  34:     ((IClientChannel)result).Open();
  35:  
  36:     return result;
  37: }
  38:     }
  39: }

Now, this kind of methods are useful in situations where one has a well-know service, configured by arbitrary name and it would be usefull to configure by that, so the method will help so. But now let focus on the first method, someone can see I use an “Enum” parameter, this is just an helper way, because first of all I don’t like literals STRING in code, ok, it’s cler that somethime are obvious to use, but normally I try to avoid, so, I like to use Enumerations as names, because them are well-know “literals” and are something like “real-piece-of-code”. I could agree with someone who can say this is just a strange way to think, but I like it. so the usage could be as this:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using XGuy.Common.Services;
   6: using XGuy.Common.Contracts;
   7:  
   8: namespace XGuy.TestConsole
   9: {
  10:     public enum Services
  11:     { 
  12:         ITestService,
  13:         IDataransferService,
  14:         SimpleDataTransfer,
  15:         FullDataTransfer
  16:     }
  17:  
  18:     class Program
  19:     {
  20:         static void Main(string[] args)
  21:         {
  22:             Services srvType = Services.SimpleDataTransfer;
  23:             //get a client proxy with simplest configuration
  24:             IDataTransferService simple = ServiceFactory
  25:                 .CreateClient<IDataTransferService>(srvType);
  26:  
  27:             Services srvType = Services.FullDataTransfer;
  28:             //get a client proxy with full configuration
  29:             IDataTransferService full = ServiceFactory
  30:                 .CreateClient<IDataTransferService>(srvType);
  31:         }
  32:     }
  33: }

In the above example I created a console, with one enumeration named Services, so I assume I can have two DataTranferService configurations, one Simple, with some configuration like BasicHttpBinding, and more, and one Full maybe with full security and NetTcpBinding enable:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <configuration>
   3:   <system.serviceModel>
   4:     <client>
   5:       <endpoint 
   6:         name="FulldDataTransfer"
   7:         binding="netTcpBinding" 
   8:         bindingConfiguration="Bindings.Full"
   9:         contract="XGuy.Services.IDataTransferService"
  10:         address="http://myServer/myServices/DataTransferService.svc"/>
  11:       <endpoint 
  12:         name="SimpleDataTransfer"
  13:         binding="basicHttpBinding" 
  14:         bindingConfiguration="Bindings.Default"
  15:         contract="XGuy.Services.IDataTransferService" 
  16:         address="http://myServer/myServices/DataTransferService.svc"/>
  17:     </client>
  18:     <bindings>
  19:       <basicHttpBinding>
  20:         <binding name="Bindings.Default"
  21:                  maxReceivedMessageSize="800000000">
  22:           <readerQuotas maxStringContentLength="65536"/>
  23:         </binding>
  24:       </basicHttpBinding>
  25:       <netTcpBinding>
  26:         <binding name="Bindings.Full">
  27:           <security mode="Transport" >
  28:             <transport clientCredentialType="Windows" />
  29:           </security>
  30:         </binding>
  31:       </netTcpBinding>
  32:     </bindings>
  33:   </system.serviceModel>
  34: </configuration>

Enjoy! Ciao!

Hi, it’s been a long very long time I have posted anything on my Blog.. and I’m really sad about that, but unfortunately I haven’t so much time in the past 2 months!!

In this past two months I’m working on a JAVA WEB project, we’re using technologies like Struts, Hibernate 3.0, Spring, Oracle Database and Servlet container implementation. I’m not shy to say this is my “Really Complete First” project in JAVA, and I have to say the experience was and is too exiting in many aspects, but sadly too.  Why I’m say this? simple, I saw a big confluence of technologies, uses, patterns, metodologies and more, I can say this could be an “Happy Develeoper Isle”, I’m too lucky cause I’m working with a colleague very cool, with strong experience and an open mind, this THE OPEN MIND took me to the “The Isle Of Thinking men” as I named by joke.

I’ve 10 years of experience, all of them in Microsoft technologies, and some marginal experience in Java, but rarely I found an open mind, a really open mind in Microsoft Technologies World, I say in the “day by day developing work”! I know peoples who I respect and I admire, with an open mind, strong experience and knowledge, but maybe, the folks in our job, they think this kind of person is a kind of “crazy scientist”, just because they goes off the lines of wich the MS developing folks adopt.

Now, in many situations, if one uses “tools” like wizards, and more, which brings the experience to 0 and to one click, if one uses them FAST, and i don’t know what else, this one could be considered a GREAT, but if this one, try to do wht his job intend to do, DEVELOPING With An Open Mind, this one could became a CRAZY or something else.

Now if I bring this one to The Java world, this one, could became not a great but nothing more that a merely very junior developer (I’m not saying you can recognize an experienced developer by how much code he writes, it’s clear experienced developer caractheristics are more complex and more in number!! now I’m saying about a way of thing, about an approach, which I really don’t like).

After some time, I realize that, what my best java collague does, if I brings that to the Visual Studio world, he could be considered a crazy man, but in the Java world he is a good senior developer. If I have to do a comparison between the world, I can see this:

  1. Java World
    1. Java developers has got a way of thinks in code reuse, but even in “developing” what they needs
    2. unfortunately Java developers has got many tools, but are lacking of strong visual tools (excuse me, I know there are many IDE’s but rarely visual tools are like Visual Studio’s ones)
    3. Java Developers can tend more to be ALT, not every time the built-in features are the better ways to do
    4. Java Developers are, from the “Junior” stage, born with an open mind and a way of think “self serviced”
  2. .NET World
    1. .NET developers rarely think in code reuse, nor to REALLY componentize things, in my experience I saw peoples who said “Do it, Do it dirty, Let it work and anything more”
    2. developers has many and many visual tools, even if this could be seen as an happy Isle, this will bring brilliant young minds to an obscure sleeping mind state (Do it, Do it fast as possible, more). Developers in this way totally lose the way in searching solutions, but first in DEVELOPING, they became Tools USERS and anything more
    3. if a .NET developer became ALT, this could happen after more and more experience, because he or she has to growth by evolution, from a BASE .NET developer to the high skyes of Open Minds, something like MATRIX WEAK-UP. If a developer try to show it’s open mind, in a microsoft world, maybe all of time he or she will be considered a Dark Obscure Scientist
    4. …..

I’m sorry about this long very long thread, but this is what was in my mind for more time. Now, me too I was in the obscure Microsoft MATRIX Kind Of Mind, but after years now I’m weak up, and I hope, I wish, I’ll do, I will spend some of my time to share experience, and anything else could be useful to peoples who wants to weak up… I know may be I’m stupid or visionist, but this is my though.

Ciao

Little little fact…

Today I took my last certification exam MS 70-547 “PRO: Designing and Developing Web-Based Applications by Using the Microsoft .NET Framework”. I had no time to prepare myself so well, but at the end it was good enough! Now I’m MCPD on Web Developing… next I’ll do exams to became MCPD on Windows Applications and maybe even on Distribuited Solutions that’s my favourite…even if it’s based on Remoting and not on WCF!

Ciao

MCPD(rgb)_504

Hi, it’s been a long I haven’t written anything on my Blog, unfortunately, I haven’t much time to do anything in this period, but I want to re-begin to write in my Blog..

Now, I’m really exited, I’m starting to do something with the new technlogies and tools that are in TOP of my learning and working curve.. I’m joking, I have to do a Course as a “Teacher” on WCF (but this, it’s one year I’m working with WCF, it’s not really new for me) and I have to begin a new project with Silverlight 2 Beta 2 and NHibernate.. I wish, I desire, to do something with a ton of the new technologies now are on the place, unfortunately I have no time, but I’m trying to read, to experiment even in my not-sleeping nights…

I Hope I could start to post something about Architecture, Silverlight, NHibernate, Entity Framework, WCF, and more….I hope…

Ciao!

Technorati Tag:

 

Recently, no sorry, it’s too much time, I saw online some discussions about using and the “best-practice-usage” of NHibernate in conjuction with WCF, and I saw so many thing about it I think someone has to say smething serious and real about this thread!

I Think I’m not one voice which can say something about it as some people in the net could do, I know many names of peoples who can be a relevant voice better than me, (I’m really new in posting to blog!) But I have some experience in this argument and so I wish to share my experience made in the past 3 months.

Now I’m working on a project built as a 3-tier app, the core technologies are surely WCF and NHibernate. I’m proud of using WCF as I see and as I heard from many people, no much people has used WCF yet (for example in my city – Rome – ), and more, WCF in conjuction with NHibernate.

I have some real experience in WCF I have made 4 or 5 big projects using that, and I have some minor experience in NHibernate, but the past 3 month gave to me a “little strong” experience on that  ” WCF + NHibernate “.

I”m working on an “intranet system” made as follow:

  • about 100 entities
  • about 50 of them are connected between them
  • about 10 services exchanging them
  • strong and large usage of ICriteria API

These are just some of the things that made up my solution, but are the more relevant I think to talk about the question:

  • My Objects are just POCOs, decorated with DataContract and used by some services.
  • My Objects are mapped as the NHibernate Best Practice would, with HBM files directly embedded in the containing assembly.
  • Mappings and pocos are physically in 2 different assemblies
  • The user Interface layer makes use of the POCOs directly by referencing the PoOCOs assembly (this is irrilevant as the nature of WCF that is Contrat Firts. Personally I hate generated entities..)

Here that’s the first thing note: everithing works correctly!

I heard and read somewhere something as “using WCF and NHibernate is impossible” or “using them togheter could made explode WCF”. Well, I think is important to understand and note what we think and wht we expect about when we say EVERITHING WORKS CORRECTLY.

Beginning with WCF, I have to remember that , it’s true WCF is born to glue some core technologies (Web Services, Remoting, …) as a “foundation” but, spending no many words, it’s made to work with “Entities” and, Entities, in the WCF world are just POCOs!

Continuing with NHibernate, it’s clear that some CORE functionalities are the MOST important things offered by the framework, I mean eg. lazy loading, collections, and so on.. These functinoalities, togheter with a fat-list of features, makes the framework on of the most important and more productive now.

Now with the advent of MS Entity Framework, the problem could be the same. I saw some Open Source projects that has been built for WCF, to give features like the “connected-local” way does to the “disconnected-distribuited” way could expect. These features makes the game as with DataSets, with Original, Modified, New and Deleted values. But came a question in mind to me, this however to work fine, surely has to “respect” some limitations? so we could take all these limitations (including maybe loosing the standards reducing the system to work just .net to .net), all the features, all the things that NH has more than Entity Framework and vice versa, and think, “if this is the situation I can use NH with WCF too” making use of some rules and some best-practice, trying to use all of the features I can without fall into a technology BREAK!

I have to say this could be a dissertation which could continue maybe for ever… I think should be clear that “the situation” drive into the solution, not all the projects are the same… So in the next post I will talk about the rules I adopted, maybe many people could find them antiquate, boring and non-elegant, but for me the most important thing is: Using NHibernate with WCF is possible!

Ciao

p.s. Sorry for my poor english…

Technorati Tag: ,

Recently I was in fight with an ORACLE “issue” I found in my day-by-day coding activity. I was lucky to discover this “issue”, after 2 hours spent in debugging, rewriting mappings, and some bad words I said to my computer, I found a solution and a post which was helpful for me.

The situation: I was mapping a simple, usual, set of Entity Properties to a related set of ORACLE NUMBER columns with no precision info. These columns were updated by a Package Procedure. So, assuming Column1 and Column2 were the comlumns I was trying to map, I mapped them in a standard way as:

   1: <!-- ... -->
   2: <property name="PropertyOne"
   3:           type="System.Decimal">
   4:   <column name="COLUMN1"/>
   5: </property>
   6: <property name="PropertyTwo"
   7:           type="System.Decimal">
   8:   <column name="COLUMN2"/>
   9: </property>
  10: <!-- ... -->

I though this could be a very easy and standard mapping, so I didnt take  so much care about, because this was a usual mapping, but I was wrong (maybe I wasn’t but Oracle were)

The problem: After I’ve done with the mapping above, I experimented a strange kind of Exception, this Exception was so strange I fall in a desperate search of all possible causes, but with no asnwers. The Exception was “Arithmetic operation resulted in an overflow“.

Now, no spending more words about my search for a cause, This situation makes me crazy, what could be the problem I asked to me? Then, as a last try, I’ve done the same operation I was doing with NHibernate in the old ADO.NET – DataSet way, and here the surprise: I FOUND THE SAME ERROR!! How was it possible, a column of NUMBER, with no precision (this assume the biggest precision supported, I though) fall in an Exception during reading from?

So after some search in the Google universe, I found a possible solution, and when I read about, it makes me too much crazy than before. I found a post in the Oracle Forum which describe a similar situation with the same exception, the answer says something like:

..We found that this is caused by a return value that has more places to the right of the decimal point than .NET can handle…Be careful of functions that return calculated values. They somethimes try to return a larger number than even ODP.NET can handle.

The solution: After days, I found this a ridiculous thing, why this could happen? Trying to better explain what above sayd, the problem was with CALCULATED VALUES maybe some times a calculated decimal can result in a decimal point number too bigger than a standard .NET decimal point number, so, it’s clear that I felt in this kind of exception, and NHibernate was innocent, because the underlying ODP.NET was the problem. I don’t want to spend much words, (I wrote more than I’ll wish), following the suggestion, this kind of bug could be solved in no many ways:

  1. change the mapping to use with a VIEW with truncated values, but I don’t like to intriduce more objects than it’s needed
  2. change the mapping to truncate values, but this fall into a “broken mapping”, a mapping which target to a single Database implementation, in my case Oracle
  3. change the procedure to outputs a well delimited  NUMBER value, but this wasn’t possible because this part of the application wasn’t written and controlled by me

So I decided for second way, in this way, just change the mapping as I will show, my code and my mapping go ahead without exceptions and any kind of problem, here is the modified mapping:

   1: <!-- ... -->
   2: <property name="PropertyOne"
   3:           type="Decimal"
   4:           formula="TRUNC(COLUMN1, 6)" />
   5: <property name="PropertyTwo"
   6:           type="Decimal"
   7:           formula="TRUNC(COLUMN2, 6)" />
   8: <!-- ... -->

In this way the resulting query result with the TRUNC function which applied as above truncate the decimal places as a desired, fixed number.

I hope this helps and could prevent anyone to a “crazy-noon” as does! ah… here is the Oracle Forum Post which gracefully helps me Arithmetic opreation…POST

Sorry for my poor and bad English, I hope I will learn well..Ciao!

Technorati Tag: ,,

Hi, recently I read many requests about how to map an Oracle RAW() Type. About 2 months ago, I was one of the those who was asking for a solution, I really cannot believe how could be possible there is not a solution, so searching in the Net I found 3 kind of solution, then, I decided what was the better for me and so I’ve implemented in my project, let’s begin.

First of all, in general a RAW column data type describe a raw binary data, generally describing a Guid. Even generally, when using a RAW data type mean, as .NET world, using a GUID, so our need is to use a RAW as GUID.

Normally there are 2 modes of reading a RAW data type, in the ADO.NET way, from a command:

  • if not is specified the RAW column returns as a Byte[] array
  • if specified, it’s possible to use during reading the RAWTOHEX(columnName) that converts from a raw byte array to a binary string, and vice versa during writing the HEXTORAW(columnName) that converts back from a binary string to a raw byte array.

but what if we want to map that column data type in a HBM mapping? Well, there are 3 ways (usually I use the last one):

  • Creating a custom NHibernate Dialect inheriting from the OracleDialect and map the Guid data type so the convertion is made while reading clearly by the engine
  • Specify a “formula” surrounding the column name and decorate the column name with the RAWTOHEX function, bu the problem came up when we want to write and we should use the HEXTORAW function
  • Creating a custom IUserType that converts to and from the RAW type.

As I said before I prefer the last one, so here is my solution: (here i will discuss the code in pieces, then in the end of the post is available the code to download)

Firts of all, we start creating a class named (in my case) RawType:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Data;
   4: using System.Text;
   5: using NHibernate;
   6: using NHibernate.SqlTypes;
   7: using NHibernate.UserTypes;
   8: 
   9: namespace MySolution.Data.Types
  10: {
  11:     public class RawType : IUserType
  12:     {

The class must inherits from IUserType, this interface instructs NHibernate we want map a specifed database column name with a custom type. Next, to correctly implement the type we need to specify the NHibernate SqlType represented by our custom type, I used the DbType.Binary in a static SqlType array variable as:

   1: private static SqlType[] types =
   2:     new SqlType[] { new SqlType(DbType.Binary) };

Next the core part of the implementation are the methods NullSafeGet and NullSafeSet that are used to handle the “raw ado read value” and translate it depending if we are reading or writing. In order, the implementation handles this situation as follow:

Reading – the value is converted from the raw binary data to System.String, this is done using the System.Guid structure that permit to create a Guid from binary array assuming a valid 32 byte array, the the ToString method with the “N” format creates a guid strings without wpecial characters

Writing - the value is converted from System.String to a raw binary representation, this is yet done using the System.Guid structure ToByteArray method

   1: public object NullSafeGet(IDataReader rs, string[] names, object owner)
   2: {
   3:     string result = null;
   4:     byte[] buffer = (byte[])NHibernateUtil.Binary.NullSafeGet(rs, names[0]);
   5:     if (null != buffer)
   6:     {
   7:         result = new Guid(buffer).ToString("N");
   8:         Array.Clear(buffer, 0, buffer.Length);
   9:     }
  10:     return result;
  11: }
  12: 
  13: public void NullSafeSet(IDbCommand cmd, object value, int index)
  14: {
  15:     if (null != value)
  16:     {
  17:         byte[] buffer = new Guid(((string)value)).ToByteArray();
  18:         NHibernateUtil.Binary.NullSafeSet(cmd, buffer, index);
  19:         Array.Clear(buffer, 0, buffer.Length);
  20:     }
  21: }

The rest part of the class is a normal implementation of a NHibernate custom type.

Now the interesting part is the hbm mapping file. We can use our type in any property even as id, declaring the generator as “assigned” because we can’t use any algorithm to assign the id value.

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
   3:                 assembly="MySolution"
   4:                 namespace="MySolution.Common.Entities">
   5:     <class name="Class1"
   6:             table="TABLE1">
   7:         <id name="Id"
   8:             type="MySolution.Data.Types.RawType, MySolution.Data">
   9:             <column name="ID" />
  10:             <generator class="assigned" />
  11:         </id>
  12:     <!-- ... -->
  13:     </class>
  14: </hibernate-mapping>

The last thing, I implemented an helper static method which generates a new “guid” from scratch.

   1: public static string GenerateNewId()
   2: {
   3:     Guid nextVal = Guid.NewGuid();
   4:     return nextVal.ToString("N");
   5: }

I hope this helps, I spend much time in finding a solution to my problem, because in the net there’s no so much on the argument, so I had to “create” a solution for my project. The next post would be another kind of serializing/deserializing binary raw to and from an Oracle Database taking care when the RAW column is not sure that contains a “well formed” binary data to build a System.Guid.

Here is the complete RawType code:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Data;
   4: using System.Text;
   5: using NHibernate;
   6: using NHibernate.SqlTypes;
   7: using NHibernate.UserTypes;
   8: 
   9: namespace MySolution.Data.Types
  10: {
  11:     public class RawType : IUserType
  12:     {
  13:         public static string GenerateNewId()
  14:         {
  15:             Guid nextVal = Guid.NewGuid();
  16:             return nextVal.ToString("N");
  17:         }
  18:         private static SqlType[] types = new SqlType[]
  19:             { new SqlType(DbType.Binary) };
  20:
  21:         public object Assemble(object cached, object owner)
  22:         {
  23:             return DeepCopy(cached);
  24:         }
  25:
  26:         public new bool Equals(object x, object y)
  27:         {
  28:             return (x == null ? false : x.Equals(y));
  29:         }
  30: 
  31:         public object DeepCopy(object value)
  32:         {
  33:             return value;
  34:         }
  35: 
  36:         public object Disassemble(object value)
  37:         {
  38:             return DeepCopy(value);
  39:         }
  40: 
  41:         public int GetHashCode(object x)
  42:         {
  43:             return x.GetHashCode();
  44:         }
  45: 
  46:         public bool IsMutable
  47:         {
  48:             get { return true; }
  49:         }
  50: 
  51:         public object NullSafeGet(IDataReader rs, string[] names, object owner)
  52:         {
  53:             string result = null;
  54:             byte[] buffer = (byte[])NHibernateUtil.Binary.NullSafeGet(rs, names[0]);
  55:             if (null != buffer)
  56:             {
  57:                 result = new Guid(buffer).ToString("N");
  58:                 Array.Clear(buffer, 0, buffer.Length);
  59:             }
  60:             return result;
  61:         }
  62: 
  63:         public void NullSafeSet(IDbCommand cmd, object value, int index)
  64:         {
  65:             if (null != value)
  66:             {
  67:                 byte[] buffer = new Guid(((string)value)).ToByteArray();
  68:                 NHibernateUtil.Binary.NullSafeSet(cmd, buffer, index);
  69:                 Array.Clear(buffer, 0, buffer.Length);
  70:             }
  71:         }
  72: 
  73:         public object Replace(object original, object target, object owner)
  74:         {
  75:             return original;
  76:         }
  77: 
  78:         public Type ReturnedType
  79:         {
  80:             get { return typeof(string); }
  81:         }
  82: 
  83:         public SqlType[] SqlTypes
  84:         {
  85:             get { return types; }
  86:         }
  87:     }
  88: }

Ciao!

Technorati: ,

« Previous PageNext Page »