Archive for the ‘Uncategorized’ Category

How to force Nuget not to update log4net to 1.2.11

Tuesday, January 31st, 2012

That’s a quick one. There’s been a new release of log4net recently that’s signed with a new key, and there­fore is incom­pat­i­ble with old ver­sion 1.2.10.

There­fore, due to near-ubiquity of the library in .NET space, it may cause some prob­lems if you hap­pen to have a depen­dency (direct or indi­rect) on it.

The mat­ters are made worse by Nuget’s default of get­ting the lat­est avail­able ver­sion of the pack­age. I dealt with this prob­lem the other day, and I saw a few peo­ple in my twit­ter stream strug­gling with the same issue.

The solu­tion is quite sim­ple. It’s not spe­cific to log4net and I’m not pick­ing on log4net here. Here’s how you can restrict Nuget’s pack­age to spe­cific ver­sion in your solution.

 

So imag­ine you install a pack­age that has a depen­dency on log4net. In this case, the depen­dency is spec­i­fied as specif­i­cally ver­sion 1.2.10 (as opposed to Nuget’s default: this ver­sion of newer).

nuget_core

If after that we install another pack­age that also depends on log4net but doesn’t restrict the ver­sion, we’ll have a problem.

nuget_log4net_fail

The pack­age we were try­ing to install doesn’t get installed. Actu­ally, even if it did, we would have a prob­lem since it most likely was com­piled against log4net 1.2.10 any­way, and if Nuget updated log4net to ver­sion 1.2.11 the app would throw an excep­tion at run­time due to mis­matched assembly.

So there is a solu­tion to restrict ver­sion of the pack­age to spe­cific ver­sion (in this case 1.2.10) as spec­i­fied in the documentation.

nuget_log4net_fail_solution

After adding allowedVersions=”[1.2.10]” we can try again and this time the pack­age will install properly.

nuget_log4net_fail_avoided

Notice it says it installed log4net 1.2.11. I checked my pack­ages folder, and project depen­den­cies and the ver­sion ref­er­enced was 1.2.10 so all is good.

Hope that helps

API design challenge – builder

Saturday, December 31st, 2011

Now that Wind­sor 3 is released I can con­cen­trate on some of my other ideas and projects. While work­ing on one of them, called Car­tog­ra­pher, I encoun­tered an inter­est­ing API design problem.

 

I have a class (a builder to be pre­cise) that has a task of set­ting up a cen­tral object (an IMap­per imple­men­ta­tion) in Car­tog­ra­pher (If you’ve ever used Aut­o­fac, it is some­what anal­o­gous to Con­tainer­Builder). What is inter­est­ing about it, is I have three goals for that class:

  1. Pro­vide API for high level con­fig­u­ra­tion and exten­sion points that are uni­ver­sal to and intrin­sic to any IMap­per implementation.
  2. Pro­vide API for low level con­fig­u­ra­tion of the default IMap­per imple­men­ta­tion that the builder cre­ates, that will meet the fol­low­ing criteria:
    1. Not force user to cus­tomize any­thing, as the default setup should be enough to get started in most cases.
    2. Allow users to eas­ily swap/extend parts of the depen­dency chain of the default mapper.
    3. Work well and be nat­ural both with and with­out IoC container .
  3. Be sim­ple and dis­cov­er­able to the users (and pro­vide good Intel­lisense experience).

How would you design the API for this class?

 

Oh, and happy new year.

Windsor 3 beta 1 is released (along with other goodies)

Monday, August 15th, 2011

The title says it all. If you can’t wait grab the bina­ries here (Wind­sor with Cas­tle Core and facil­i­ties) and here (just Core). Nuget pack­age will hope­fully fol­low soon.

What’s in it?

This is a major release and there’s quite a lot of new fea­tures, as well as some sig­nif­i­cant changes under the cov­ers. There’s a high level overview of high­lights for the release in the wiki, so please have a look there. More detailed changelog, and list of break­ing changes is avail­able as part of the package.

Remem­ber it’s a beta release. Doc­u­men­ta­tion and sam­ples are still being updated and some fea­tures are not yet imple­mented or not fully baked. How­ever it is very impor­tant that you don't wait for the final release to upgrade, so that we can find and fix all the issues before final release. I'm not ask­ing you to use it in pro­duc­tion, but I'd really appre­ci­ate if you'd take the time to branch your apps, try to upgrade, run your unit tests, play with new ver­sion, and report any issues you may find. And ask your col­leagues, friends and ran­dom peo­ple on the street to do the same!

And if you find any issues, do report them.

Have fun and happy cod­ing,
I hope you like it

IronRuby, Nu project and Launchy at your service

Saturday, September 4th, 2010

There’s been some buzz lately about the nu project that uses ruby gems infra­struc­ture to let you quickly and eas­ily grab lat­est ver­sion of com­mon (and not so com­mon) open source libraries with­out hav­ing to go and hunt for them.

All you need to do, is to open a com­mand line, type

nu install foo

and you’ll get the project foo installed on your machine.

If you’re lazy, like me this may seem like too much. If you’re a Launchy user, like me – I have a solu­tion for you.

launcyh

Go to plu­g­ins, select run­ner and add entry for nu as on the screen­shot above. For “Pro­gram” sec­tion type path to your nu.bat file which you’ll find in your Ruby, or Iron Ruby install direc­tory. As argu­ments type $$ which means “what­ever I pass” and you’re done.

Now you can open Launchy, type nu <tab> install project-name and few moments later the selected project is on your hard disk. Sim­ple, hope­fully useful.

nuj

dotless

Castle Windsor (incl. Core with DynamicProxy and Dictionary Adapter) v2.5 final is out

Sunday, August 22nd, 2010

Exactly one month after beta 2, I’m happy to announce that Wind­sor, as well as Cas­tle Core (which now includes Dynam­icProxy and Dic­tio­nary Adapter) 2.5 are offi­cially released.

Sin­gle .zip con­tains the fol­low­ing versions:

  • .NET 3.5 (sp1)
  • .NET 4.0
  • .NET 4.0 Client Profile
  • Sil­verlight 3
  • Sil­verlight 4

Changes, changes, changes

For the list of changes see announce­ment for beta 1, and beta 2 or changes.txt file in the pack­age. Since beta 2 the fol­low­ing changes were made:

  • debug­ger view sup­port has been extracted to a sep­a­rate sub­sys­tem (ICon­tain­erDe­bug­gerEx­ten­sion­Host) and can be extended by users code via ICon­tain­erDe­bug­gerEx­ten­sion and IComponentDebuggerExtension
  • call­ing IHandler.TryStart will no longer silently ignore all the exceptions.
  • added Col­lec­tion­Re­solver which is a more gen­eral ver­sion of ArrayRe­solver and ListRe­solver and sup­ports in addi­tion ICollection<Foo> and IEnumerable<Foo>
  • fixed issue where depen­den­cies would not be cleaned up when com­po­nent cre­ation failed
  • fixed issue where startable com­po­nent would be cre­ated twice when prop­erty depen­dency could not be resolved
  • pass­ing argu­ments to ILazy­Compo­nent­Loader (see breakingchanges.txt)
  • fixed bug that caused excep­tion when prox­ied com­po­nent and it's prox­ied prop­erty depen­dency shared interceptor

Sam­ples

For now we have a sin­gle sam­ple appli­ca­tion (Sil­verlight 4 app), cre­ated by Hadi Eskan­dari. You’re still wel­come to con­tribute more apps, and hope­fully soon we’ll have more of them.

New issue tracker

While not strictly related to the release, we also deployed a new issue tracker, which should be much eas­ier to use.

Down­loads

The pack­age is here (Core with Dynam­icProxy and Dic­tio­nary Adapter) and here (Wind­sor with Log­ging Facil­ity and Syn­chro­nize Facil­ity). Enjoy.

Mapping different types with NHibernate — IUserType

Monday, October 12th, 2009

warninglabel_thumb[1]

Recently I had a prob­lem with the appli­ca­tion I’ve been work­ing on. One of entity types in my domain had a prop­erty of type uint. Not a big deal, until you want to store it in Microsoft SQL Server data­base which does not sup­port unsigned types. I’ve been scratch­ing my head for a moment and then I found a solu­tion – let’s map it as long in our data­base. Since long can rep­re­sent any legal value of uint, we should be all good, right? So let’s do it.

public class ClassWithUintProperty
{
    private Guid Id { get; set; }
    public virtual uint UintProp { get ;set; }
}

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="NHibernate.Test"
                   namespace="NHibernate.Test">
  <class name="ClassWithUintProperty">
    <id name="Id"/>
    <property name="UIntProp" not-null="true" type="long" />
  </class>
</hibernate-mapping>

 

"Hous­ton, we've had a problem"

All good. At least until you try to fetch saved value from the data­base. When you do, you’re up for an unpleas­ant surprise:

System.InvalidCastException: Spec­i­fied cast is not valid.

NHibernate.PropertyAccessException: Invalid Cast (check your map­ping for prop­erty type mis­matches); set­ter of NHibernate.Test.UIntAsLong

The excep­tion is a result of how NHiber­nate opti­mizes prop­erty access and quirks of mix­ing dif­fer­ent con­ver­sion oper­a­tors (unbox­ing and numeric con­ver­sion in this case) and are not really inter­est­ing. What’s impor­tant, is that we approached the prob­lem from the wrong angle.

What we’re deal­ing with here, is inabil­ity of our data­base engine to deal with datatype in our model, which we were try­ing to solve by push­ing this onto NHiber­nate with­out telling it some­thing is ‘”wrong”. While NHiber­nate is smart, it’s work­ing based on a set of explicit infor­ma­tion, so what we need to do, is to be explicit about what we want it to do.

There are two places where we can tell NHiber­nate about it.

  • IUser­Type, which will explic­itly han­dle the map­ping from uint in our model to long in the DB
  • cus­tom Dialect which will basi­cally lie to NHiber­nate telling it “yeah, sure this DB sup­ports uints – whole dozens of ‘em!” and do some work under the cov­ers to live up to its promise. (not shown in this post).

 

Enter IUser­Type

IUser­Type is an exten­sion point in NHiber­nate that let’s you plug in to the map­ping process and han­dle it your­self. The inter­face is quite big, but there’s very lit­tle real logic there:

public class UIntAsLong:IUserType
{
        public SqlType[] SqlTypes
        {
            get { return new[] { SqlTypeFactory.Int64 }; }
        }
 
        public Type ReturnedType
        {
            get { return typeof( uint ); }
        }
 
        public bool IsMutable
        {
            get { return false; }
        }
 
        public int GetHashCode( object x )
        {
            if( x == null )
            {
                return 0;
            }
            return x.GetHashCode();
        }
 
        public object NullSafeGet( IDataReader rs, string[] names, object owner )
        {
            object obj = NHibernateUtil.UInt32.NullSafeGet( rs, names0 );
            if( obj == null )
            {
                return null;
            }
            return (uint)obj;
        }
 
        public void NullSafeSet( IDbCommand cmd, object value, int index )
        {
            Debug.Assert( cmd != null);
            if( value == null )
            {
                ((IDataParameter)cmd.Parametersindex).Value = DBNull.Value;
            }
            else
            {
                var uintValue = (uint)value;
                ( (IDataParameter) cmd.Parametersindex ).Value = (long) uintValue;
            }
        }
 
        public object DeepCopy( object value )
        {
            // we can ignore it...
            return value;
        }
 
        public object Replace( object original, object target, object owner )
        {
            // we can ignore it...
            return original;
        }
 
        public object Assemble( object cached, object owner )
        {
            // we can ignore it...
            return cached;
        }
 
        public object Disassemble( object value )
        {
            // we can ignore it...
            return value;
        }
 
        bool IUserType.Equals( object x, object y )
        {
            return object.Equals( x, y );
        }
} 

There are really two parts of the code that are inter­est­ing. Sql­Types / Returned­Type prop­er­ties which tell NHiber­nate which types to expect on both sides of the map­ping, and the Null­SafeGet / Null­Safe­Set meth­ods which per­form the actual conversion.

Now we just need to plug our cus­tom user type to the map­ping, and it goes like this:

<?xml version="1.0"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="NHibernate.Test"
                   namespace="NHibernate.Test">
  <class name="ClassWithUintProperty">
    <id name="Id"/>
    <property name="UIntProp" not-null="true" type="Foo.Namespace.UIntAsLong, Foo.Assembly" />
  </class>
</hibernate-mapping>

Tech­no­rati Tags:

Adjusting NHibernate mapping for tests

Thursday, August 13th, 2009

As nice as SQLite is for tests it is very sim­ple data­base, and it does not have all the options ‘big’ data­bases pro­vide (for­eign key enforce­ment!). I don’t think there’s much you can do about this issue, but there’s more.

SQLite does not sup­port all the map­pings you can have. I bumped into this issue when work­ing with map­ping sim­i­lar to described in this post. Basi­cally when you try to cre­ate schema from this mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
                   namespace="ConsoleApplication1" 
                   assembly="ConsoleApplication1">
  <class name="Invoice">
    <id name="Id">
      <generator class="guid.comb" />
    </id>
    <property name="InvoiceRtfString" type="StringClob">
      <column name ="RtfText" sql-type="nvarchar(MAX)"/>
    </property>
    <property name="ScannedInvoiceJpg" type="BinaryBlob">
      <column name ="JpgData" sql-type="varbinary(max)" />
    </property>
  </class>
</hibernate-mapping>

You’ll get an error:

SQLite error near "MAX": syn­tax error

That’s because SQLite does not know how to han­dle nvarchar(max) or varbinary(max). It has its own types for that – TEXT and BLOB. So you’re either stuck, or have two sets of map­pings – one for tests for SQLite, one for pro­duc­tion, for SQL Server. But wait, there’s third option!

In the pre­vi­ous post, you may have noticed, that in DbTests­Base Init method I call:

new Remapper().Remap(configuration);

Remap­per is my rem­edy for that prob­lem. It’s a sim­ple class that tra­verses the map­ping look­ing for incom­pat­i­bil­i­ties and adjusts it on the fly before cre­at­ing ses­sion fac­tory and schema. This lets you have sin­gle map­ping (be it XML or Flu­entNHiber­nate) while still using SQLite for tests.

The class looks like this:

public class Remapper
{
    private IDictionary<string, String> map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 
    public Remapper()
    {
        map.Add("varbinary(max)", "BLOB");
        map.Add("nvarchar(max)", "TEXT");
    }
 
    public void Remap(Configuration configuration)
    {
        foreach (var classMapping in configuration.ClassMappings)
        {
            this.Remap(classMapping.Table);
        }
    }
 
    private void Remap(Table table)
    {
 
        if (table.Name.Contains("."))
        {
            // found on http://www.nablasoft.com/alkampfer/index.php/2009/07/24/manage-in-memory-nhibernate-test-with-sqlite-and-database-schema/
            // this is a table with schema
            table.Name = table.Name.Replace(".", "_");
        }
 
        foreach (var column in table.ColumnIterator)
        {
            this.Remap(column);
        }
 
    }
 
    private void Remap(Column column)
    {
        if (string.IsNullOrEmpty(column.SqlType))
        {
            return;
        }
 
        string sqlType;
        if (!this.map.TryGetValue(column.SqlType, out sqlType))
        {
            return;
        }
 
        column.SqlType = sqlType;
    }
}

It is very sim­ple and basic, because I cre­ated it for my very spe­cific needs, but with lit­tle effort you could extend it to han­dle more incompatibilities.

Tech­no­rati Tags: ,

Framework Tips XIII: Testing Random code

Tuesday, August 4th, 2009

Ques­tion

How do you test code that is ran­dom. For exam­ple say you have a class that allows some action with 60% probability:

public class UsingRandom
{
    private Random generator;
    public double probability = 0.6D;
 
    public bool ShouldAllow()
    {
        return generator.NextDouble() < probability;
    }
}

How do you unit test that?

 

Answer

The answer is stag­ger­ingly sim­ple – you fake it. Raise your hand if you knew that meth­ods in the Ran­dom class are vir­tual (I didn’t). Ok, now you can put your hand down, both of you.

virtual_random

With that knowl­edge, all you have to do is to inject an appro­pri­ate fake into the class dur­ing your test, and you’re done.

 

Tech­no­rati Tags: ,

Gallio NCover integration

Wednesday, June 25th, 2008

I just love Gal­lio. It’s my per­sonal Best New Project of the Year. It amazes me how with only this:

Gallio_NCover_xml

I get this:

Gallio_NCover 

Notice that those are NUnit tests, no MbUnit.

Pure gold.

Tech­no­rati Tags: , ,

Three times have I received The Order of Lenin…

Wednesday, May 21st, 2008

I just came back from pre-premiere screen­ing of Indi­ana Jones and the King­dom of the Crys­tal Skull. To make it short: I haven't had such fun in cin­ema for a long time. If you liked the old movies — you'll love this one — it cer­tainly is not the worst of them. Despite of the fact that the whole movie is just one giant prod­uct place­ment of refrig­er­a­tors ;) Even Shia LaBeouf is tolerable.

The movie is very well bal­anced, with lots of action, with­out long boring-ish moments like "and the Tem­ple of Doom", and with­out cheap jokes, like "and the Holy Grail". It has lots of ref­er­ences to pre­vi­ous movies though, so it might be a good idea to see them once again to get the most out of this one.

To sum it up — I highly rec­om­mend it.

Tech­no­rati Tags: ,