PrimeDigit – A Design Blog by Will Shaver

June 16, 2008

CriteriaByLongAlias

Filed under: NHibernate,c# — Will @ 9:01 am

This simple function cleans up a lot of the Alias sillyness I have fought with in NHibernate.

        public static ICriteria CriteriaByLongAlias(this ICriteria criteria, string field)

        {

            ICriteria byAlias = criteria.GetCriteriaByAlias(criteria.Alias + “_” + field) ??

                                criteria.CreateCriteria(field, criteria.Alias + “_” + field);

            return byAlias;

        }

It is used any time you would previously call CreateCriteria and pass an alias.
Before:
session.CreateCriteria(typeof (Product)).CreateCriteria(“Orders”,”Product_Orders”);
After:
session.CreateCriteria(typeof(Product)).CriteriaByLongAlias(“Orders”);

The alias part is done automatically based on the criteria path. The advantage is that it works recursively, allowing for multiple criteria to be created, and then referenced without duplicates.

ICriteria criteria = session.CreateCriteria(typeof(Product)).CriteriaByLongAlias(“Orders”).CriteriaByLongAlias(“Customer”).Add(Expression.Eq(“Name”, “Ace Hardware”));
criteria.CriteriaByLongAlias(“Orders”).Add(Expression.Eq(“OrderNumber”,12354));

etc.

Note that in order for it to work, you have to create all your subcriteria with it.

-Will

June 4, 2008

Cool Code – Assembly.FindType

Filed under: c# — Will @ 3:06 pm

Here’s an extension to Assembly that I found useful for finding a type. I recommend doing
typeof(TypeInAssembly).Assembly.FindType(“typename”);

    public static class AssemblyExtensions

    {

        public static Type FindType(this Assembly assembly, string typename)

        {

            return assembly.FindTypes(typename).FirstOrDefault();

        }

 

        public static Type[] FindTypes(this Assembly assembly, string typename)

        {

            Type[] types = assembly.GetExportedTypes();

            List<Type> found = new List<Type>();

            foreach(Type type in types)

            {

                if(type.Name == typename)

                {

                    found.Add(type);

                }

            }

            return found.ToArray();

        }

    }

Powered by WordPress