Archive for the tag 'Development'

CSLA - first base was fun, but I want a relationship

The scene opens on a typical fall Saturday evening at the local sports bar filled with enthusiastic football fans cheering loudly at the myriad of TV screens scattered around. In one small corner sitting around a high table is a group of people visiting about software development. Two guys, eager to make friends, walk up introduce themselves and let slip they’ve been developing software with CSLA for the past few years, and are looking for redemption.” The rest of the table then looks at each other and responds in chorus, “I’m Sorry!”

 

The shock on their faces at the collective “I’m Sorry” was a bit much. They knew some people have very differing opinions about different frameworks and tools, but hearing it confessed out loud was a breath of fresh air.

Recently our development team decided to stop developing with the CSLA framework. Before I get into specifics, I want to be very clear about something up front. I have no problem with people that continue to use CSLA. We used CSLA for nearly 4 years and it has worked in way it was designed.

 

While Hiren and I were at KaizenConf in Austin we made sure to find a few minutes each evening before getting caught up with a large group, to recap the day and share some new things we each learned. One of these nights while relaxing and evaluating what we’d been learning we came to the conclusion that it was time for us to step away from new development with CSLA and migrate existing codebases as well. Over the past week we have been outlining and discussing these ideas and why we have made the decision to move away from CSLA.

 

It all started a few months ago when we first started getting introduced to the Alt.Net ways of developing software. What I mean by the Alt.Net ways are things like S.O.L.I.D. principles, ORM use, unit testing, Domain Driven Design, Mocking, TDD, etc… All of this has really changed the way we think about and develop software. Even before this though Hiren and I made a very dangerous combination of developers because we are never satisfied with a piece of code once it is written, we usually have to talk one another into just leaving it alone because it works and is as good as it needs to be to get the job done.

 

There are several driving forces behind this decision, but the primary one is that our CSLA business objects just leave a bad taste in our mouth. Our systems are moderately complex and it is not uncommon at all to have a class with 1500 – 2500 lines of code, in fact that is probably an average line count in most business objects. The other thing that really smells to us is that the “model” contains a lot of stuff that is not directly related to the model, namely data access.

 

I would like to take a minute to point out some of the things I really like and will miss about CSLA, and some of the other reasons for making the switch.

 

 

CSLA, I will miss some of you:

  • Validation Rules System
  • Data binding Support
  • Combo of these == reach UI validation for user
  • Good set of guiding principles and samples to get started with.
  • Rocky’s Books!

I won’t miss these parts though:

  • Data Access code in business object
  • Difficult to mock out data access in mocking
  • N-Level undo – I never, ever used this but had to contend with it, like it or not
  • “Super” Classes

These are purely my opinion so take them as they are. I still think CSLA has a place for some people and unlike others I have run into on the internet, I will not bash you or think you are stupid for using it. CSLA was an excellent stepping stone for us; it introduced and really engrained the Object-Oriented Programming style of thinking into our minds. I/we just feel like we have matured to a new level of development through better understanding of our software development process and how apply those skills to our situation.

 

We are still learning and don’t yet know exactly what our development style is going to be end-to-end on this project. We have a long way to go before we are completely comfortable with all these new tools. Luckily, the Alt.Net community seems to be an open and accepting group and nearly everyone is willing to help us out along the way.

What I do know is that no team can just take what one person or one book says and do it that way. It won’t work. What we are doing is educating ourselves on different practices and tools and using what works for us, we do a lot of spikes right now. We are also building our domain model with POCO’s which gives us a great amount of flexibility in the infrastructure and presentation layers of our system. As we continue this process I will post successes and failures here on my blog.

Strongly typed Collections of Abstract Objects

Some of you know that we are in the process of not using Csla anymore, this is a decision that just seems logical for us, but that is another post. I need a little help implementing a problem in my domain. Now the sample I am posting is out of a dumbed down version I have been using to spike with. Take a look at the following class diagram and then I will explain what is going on and what my problem is:

Order-ClassDiagram01

What is going on here you ask? Order is the primary object type, but it is abstract. I have maybe 7 different types of orders, service order, make order, repair order, etc… each order has several attributes that are always present on every order. What makes each order unique is the attributes that are not shared between all orders. This is why I have decided to use inheritance.

One of the items that are common between all types of orders is that they all have many parts. However, I want the base Order class to have a collection of base OrderPart objects. OrderPart is the mapping object in between Order and Part for the Many To Many relationship, I am using an object because this association has state of it’s own. Now to complicate matters even more, each concrete Order can have a different concrete type of Part and OrderPart assigned to it.

I have the model all setup and Have written some tests against it as I wrote it, not really test first but hey, I am spiking here. So below is one of the tests that shows most of this in action.


public void CanCreateOrderWithCustomerAndParts()
{
var order = new CustomOrder();
order.Customer = new Customer
{
Name = "John Smith",
Address =
new Address
{
Street = "45623 Easy",
State = "TX",
City = "Dalals",
ZipCode = "73884"
}
};
order.OrderNumber = "Y984939";
order.Amount = (decimal) 1234.33;
order.CustomOrderDescription = "Testing adlkfjl 123";
order.Parts =
new List
{
new CustomOrderPart
{
Part =
new CustomPart
{
PartNumber = "Part456sdf34",
Description = "Test Partasd 87",
CustomPartText = "TEST",
},
Quantity = 12
},
new CustomOrderPart
{
Part =
new CustomPart
{
PartNumber = "PARTWITHNULLPULLLOCATION",
Description = "Test Part 848sasd8243",
CustomPartText = "TEST",
},
Quantity = 251
}
};

With.Transaction(() => Repository.Save(order));

Order createdOrder = Repository.Get(order.Id);

Assert.IsNotNull(createdOrder);
Assert.AreEqual(2, createdOrder.Parts.Count);
}

Don’t make fun of my test code, like I said, it’s a spike. But when I create a CustomOrder I am creating Parts as a new List<OrderPart> which is how it is implemented. But then I had new CustomOrderParts and CustomParts into that collection. NHibernate will persist this information correctly into the database and will retrieve it correclty from the DB. So seemingly all works fine right, sure I guess. Maybe it is just because I have been in Csla land so long that I don’t know any different but what I am really missing is being able for the concrete order object to know what concrete type of  OrderPart is contained in the parts collection. As I wrote that I just kicked myself, if that isn’t a violation of Seperation of Concerns I don’t know what is, or is it? I mean Order or a concrete Order is basically an Aggregate Root in DDD terms so it is the responsible entry point into the chain/web of objects that make up the aggregate.

So, for my real question which I am not sure of now, How would you tackle this design problem? How do you handle child collections? Am I just way off the reservation?

NHibernate Caching Explained, finally!

Gabriel Schenker has just posted an excellent article explaining in detail how to the 1st and 2nd level cache in NHibernate works. This is a long overdue article on caching that will greatly benefit the community. The article also explains the differences between Get(id) and Load(id) when retrieving entities through NHibernate. I am recommending this article because it is an in depth look at one of the pieces I covered earlier on Ayende’s session from KaizenConf.

DDD - Just reading book

When I got back from #KaizenConf I had to order a copy of Eric Evans book, Domain-Driven Design: Tackling Complexity in the Heart of Software. Main reason being that I went to a DDD session Dave had and learned a lot that just made sense so I figured it was a must have. So I ordered it, got it and have been reading it the majority of the weekend and I must say it is a very good book. For me though a lot of has been just giving formal names to the things we were already doing. Most of this is because we are a small team/company so we have always been the developers/business analysts etc…. But overall very good so far with good emphasis in the right places I think.

I have also lost my virginity (and you should too)

UPDATE: I have lost my virginity in regards to attending my first software conference, just in case that wasn’t clear… you know who I am talking to.

I just read Brian Mavity’s latest post and am obviously rowing the same proverbial boat that he is. This is not only my first software development conference but the first software development conference our company has ever sent anybody to. I personally have already taken more away from this than I ever imagined. Just sitting around at dinner or socializing with the same people whose blogs I follow is somewhat intimidating, but they are all very welcoming and want to help us new guys get going. I have had conversations (okay, mostly absorbing) with Ayende, Chad Myers, and Jeremy Miller. I have also been able to speak one on one with others and will most definitely get the opportunity to do some more.

Same as Brian Mavity, if you your company does not care enough about their development team to spare a little time and money to get you involved, you should consider finding a place that does or making your voice heard better to accomplish this.

I am really looking forward to the next few days worth of activities.

KaizenConf Workshops – Advanced NHibernate

As some of you know I am attending KaizenConf for the next few days. I am going to use my blog as my notepad as I take notes during different workshops and sessions. My note taking skills sometimes have a lot to be desired so be patient if these notes look very sketchy. I will try my best to come back through and make sense of them later.

Advanced NHibernate

I am currently sitting through Ayende’s workshop on Advanced NHibernate and there is some really good stuff going on here. Three of the topics I have found most interesting is Multi-Tenancy, Full text indexing with NHibernate Search, and caching with NHibernate. NHibernate search is a project that combines Lucene, a proven java index tool, and NHibernate to alleviate strain on the database engine by keeping indexes on disk and performing queries on that data faster. Indexing is accomplished by decorating entities with attributes. Of all these topics caching with NHibernate has really grabbed my attention as it probably has the greatest results for the applications I am currently working.

Caching with NHibernate

1st Level cache –Contains Identity Map – Session – Single instance of an object in a particular session

2nd Level Cache – contains the SessionFactory – lives for the entire application lifetime, it also has 4 levels of cache within it:

timestamp
query cache
collection cache
entity cache

 

Caching Configuration

Enable query cache <property name=”cache.use_second_level_cache”>True</property> in NHConfig – A single on off switch in the application to enable/disable caching is not a good solution because caching is complex and could affect business rules and performance. So you have to enable caching for a specific entity by using Cache_usage = CacheMode (ReadWrite for Ayende’s samples) in the entity mapping file. The NHibernate cache hashtables are stored like below:

Entities Cache:
————————-
Blog#1 : { Name: “…”}
Post#1 : {…}
Post#2 {…}

Collection Cache
—————————
Blog#1.Posts { 1,2,3,4,5,6} – stores id’s only

Query Cache:
—————————
“select top 5 * from Post” : {1,2,3,4} // stores id’s only

Ayende used his blog sample for all of the code examples today. When he put caching on the Blog, and the collection of posts in the blog map and on the post entity the fewest calls to the database occurred. To enable query caching the property cache.use_query_cache = true in the config file.

Session.Load vs Session.Get

Load == I know the entity exists in the database, it returns a proxy to the object. Throws an exception if the object is not lazy loaded and cannot be found.

Get == NH really goes to the database and fetches a row or throws an exception if it does not exist.

Which one of these to use depends on the business rule for the entity.

 

NHibernate Contrib project descriptions

NHibernate cache libraries:

PrevelanceCache – persistent caching for smart client applications

SysCache – using ASP.net caching – gives it the ability to put things in the cache and forget about it – only works if you have one machine.  Other wise you get cache poisoning.

SysCache2 – ASP.net caching in the farm – maybe application is not the only thing that updates the database. This is good when the application is not the sole owner of the database.

MemCache – a distributed hashtable, thats it basically it is distributed caching.– Server sitting on TCP with a hashtable – the Client caches the key and always goes back to same server in farm for cache retrieval. Very simple, works very well. This is also known as MemCacheD and is the same caching strategy that Facebook uses.

SharedCache – SharedCache from CodePlex

Velocity – From Microsoft – more complex than memcache, more options but they validate the cache space you have.

 

Other NHibernate Contrib Projects

NHibernate.Linq – pretty good, handles most of the common scenarios, does not handle the crazy scenarios that are capable in LINQ. Currently working on a fully functional LINQ library.

NHibernate.Validator– Just as you can specify constraints in SQL Server. You can specify constraints in your mapping file and the validator will validate that for you.

Spatial – GIS applications

Shards – partition the data across multiple db’s – written by Google to deal with problem of having multiple database. You can teach NHibernate a sharding strategy so that it knows which database to use. This is a strategy that is used by companies such as Facebook.

 

Another very interesting topic Ayende talked about is self optimizing queries. This would be used by session.Future<TYPE>() you could use this in your repositories on all lists/CreateCriteria methods. This creates a MultiCriteria which returns multiple result sets in one database trip. This is very similar/exactly like multiple result sets in stored procedures.

IRepository Code

This is by request from Frank Mao, he was wanting me to post up the code I am using for IRepository<T> so here it is:


public interface IRepository<T>
{
//IList<T> FetchList();
ICriteria CreateCriteria();
T Get(object id);
void Load(T obj, object id);
void Delete(T entity);

void DeleteAll();
void DeleteAll(DetachedCriteria where);
T Save(T entity);
T SaveOrUpdate(T entity);
T SaveOrUpdateCopy(T entity);
void Update(T entity);
long Count(DetachedCriteria criteria);
long Count();
bool Exists(DetachedCriteria criteria);
bool Exists();
IList<T> FindAll(DetachedCriteria criteria, params Order[] orders);
IList<T> FindAll(Order order, params ICriterion[] criteria);
IList<T> FindAll(Order[] orders, params ICriterion[] criteria);
T FindFirst(params Order[] orders);
T FindFirst(DetachedCriteria criteria, params Order[] orders);
T FindOne(params ICriterion[] criteria);
T FindOne(DetachedCriteria criteria);

ProjT ReportOne<ProjT>(ProjectionList projectionList);
ProjT ReportOne<ProjT>(DetachedCriteria criteria, ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, ProjectionList projectionList);
IList<ProjT> ReportAll<ProjT>(ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(DetachedCriteria criteria, ProjectionList projectionList, params Order[] orders);
IList<ProjT> ReportAll<ProjT>(bool distinctResults, DetachedCriteria criteria, ProjectionList projectionList, params Order[] orders);
}
}

I should note that this is a slightly modified version of IRepository that I got from the UnitOfWork tutorial code that is posted here: http://hibernatingrhinos.googlecode.com/svn/trunk/UnitOfWork/src/NHibernateRepository/

Csla Project Tracker + ObjectFactory + Altdotnet = Goodness

I will start off by giving my regular disclaimer, I am not an expert on this, however, I am also not an idiot either.

 

How It Was

 

We have been using Csla as a business object framework for about 3 years now and have had good results with it. That and we like things to just work and it does. Now a few months ago we started to get introduced to the altdotnet way and have seen the light and the need for many of the principles of altdotnet in our organization, it just makes sense. A few weeks ago Rhockford Lhotka release the beta version of Csla 3.6 and with it he has introduced support for an extensible ObjectFactory. This custom ObjectFactory takes the place of the DataPortal_XYZ() methods in the business object.

 

Now with the old way I had to make an object and write at least 3 lines of data access code for every property. This is cumbersome and just plain stinks. But good news! There is a better way.

 

The Better Way

 

So with this new ObjectFactory in Csla I can now spread some altdotnet goodness into my Csla projects. To be more specific here is what I have done, this has increased the dependencies of the project but has made the code much more flexible and easier to test.

Hopefully this little overview has intrigued you enough to go download the source code for the Csla sample redone with an ObjectFactory implementation. The source code and zip file are available at http://code.google.com/p/cslaptrackerfactory/ I will update the repository as I make changes/ additions to the code. I have created this as an open source project because I know that my method is not the only method and hopefully we can collectively come up with a way to use Csla with altdotnet goodies in a more standard way. So with that said, if you want to join the project, drop me a line.

 

I will post more articles that go in depth on how/why I did things a certain way in this project later, I hopw.

ALT.NET a College Curriculum?

There has been a lot of discussion recently on the ALT.NET list about how the ALT.NET way is so hard and complicated that it may be equivalent to a college computer science curriculum. This all started as a discussion that was geared towards building some type of cascading curriculum guide to ALT.NET software engineering principles such as TDD, S.O.L.I.D, continuous integration, unit testing, composition over inheritance, etc… I agree with this totally, We need to make some type of curriculum guide to ALT.NET principles. I am fairly new to ALT.NET and I am also fairly young. Where I work there are only two developers and we are also testers/designers/everything so when we decided that we could write better software by following the ALT.NET principles we had a hard time finding a starting place amongst all the available information. It is simply overwhelming when you are first starting, and I know we have been talking about easing the entrance barrier, but it’s just not that easy. There has to be some difficulty or is the reward is not as great in the end. However, I do believe that some type of curriculum guide would be a great tool for everyone involved with ALT.NET at any level. I think the best thing about this chart is just to show how the different principles build on each other and relate to each other so you have a reference point you can find yourself on.

Now back to the discussion on Computer Science (CS) curriculum in colleges, I graduated from a small college in Oklahoma with a degree in CS a few years ago. I personally gained a lot from college because I had a professor who had previously worked in the real world, and I worked in the real world developing software while in college so we could have intelligent conversations that only a few other students understood. This was great for me, a self motivator, but not for everybody else. I was able to demand the one on one time that I needed and to ask questions and have problems that forced the “super” students into thinking about problems other than writing a counter in a nested loop. I have now been asked to teach some software courses at the college and help, along with other alumni to revamp the curriculum that is taught in the school. In January I will begin teaching two semesters worth of ALT.NET curriculum. This will be a huge leap ahead for the students, but also for the faculty as I feel so much college faculty is out of touch with the real world anyway.

Ultimately though I think what college is really designed to do is teach students HOW to think and HOW to learn since a college cannot be expected to keep up with all the latest and greatest trends in Software engineering but it can teach students some higher level principles such as ALT.NET or at least get them started down the right path to learning ALT.NET.

SQL Server Timestamp field and Fluent-NHibernate

This morning I was trying to do a Version mapping with Fluent-NHibernate on a timestamp column in a SQL database, this didn’t work so good right out of the box so I dug around and found some information here and there and once I pieced it together it all worked.

First off the mapping:


public class ProjectMap : ClassMap<Project>, IMapGenerator
{
        public ProjectMap()
        {
            WithTable("Projects");

            Id(x => x.Id)
                .GeneratedBy
                .GuidComb()
                .WithUnsavedValue("00000000-0000-0000-0000-000000000000");

            Map(x => x.Name)
                .WithLengthOf(50)
                .CanNotBeNull();

            Map(x => x.Started);
            Map(x => x.Ended);
            Map(x => x.Description);

            Version(x => x.TimeStamp)
                .TheColumnNameIs("LastChanged");
          }

}

public override VersionPart Version(System.Linq.Expressions.Expression<Func<ProjectResource, object>> expression)
{
     var versionPart = new VersionPart(ReflectionHelper.GetProperty(expression));

     versionPart.SetAttribute("type", "ProjectTracker.Library.Mapping.UserTypeTimestamp, ProjectTracker.Library");
     versionPart.SetAttribute("generated", "always");
     versionPart.SetAttribute("unsaved-value", "null");

     AddPart(versionPart);
     return versionPart;
}
 

The main thing here is the overridden Version method. What this override is doing is setting up a few attributes required to make this all work properly, I think most of them are self explanetory. Inside this method is a set attribute method that sets the type of the timestamp to UserTypeTimestamp. The coded for this class follows below:

UserTypeTimestamp Class:


public class UserTypeTimestamp : IUserVersionType
    {
        #region IUserVersionType Members

        public object Next(object current, ISessionImplementor session)
        {
            return current;
        }

        public object Seed(ISessionImplementor session)
        {
            return new byte[8];
        }

        public object Assemble(object cached, object owner)
        {
            return DeepCopy(cached);
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Disassemble(object value)
        {
            return DeepCopy(value);
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public bool IsMutable
        {
            get { return false; }
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            return rs.GetValue(rs.GetOrdinal(names[0]));
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            NHibernateUtil.Binary.NullSafeSet(cmd, value, index);
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public System.Type ReturnedType
        {
            get { return typeof(byte[]); }
        }

        public SqlType[] SqlTypes
        {
            get { return new SqlType[] { new SqlType(DbType.Binary) }; }
        }

        public int Compare(object x, object y)
        {
            byte[] xbytes = (byte[])x;
            byte[] ybytes = (byte[])y;
            if (xbytes.Length < ybytes.Length)
            {
                return -1;
            }
            if (xbytes.Length > ybytes.Length)
            {
                return 1;
            }
            for (int i = 0; i < xbytes.Length; i++)
            {
                if (xbytes[i] < ybytes[i])
                {
                    return -1;
                }
                if (xbytes[i] > ybytes[i])
                {
                    return 1;
                }
            }
            return 0;
        }

        bool IUserType.Equals(object x, object y)
        {
            return (x == y);
        }

        #endregion
    }

Now for the Business object change this:

private byte[] timeStamp = new byte[];

To this:


private byte[] timeStamp;
internal byte[] TimeStamp
{
     get { return timeStamp; }
     set { timeStamp = value;}
}

With the addition of the class and an internal Property so NHibernate can access the data in the timestamp everything works pefectly to implement optimistic concurrency with Fluent-NHibernate and SQL Server timestamp fields.

Next Page »