Angel \”Java\” Lopez on Blog

October 7, 2011

The Repository Pattern: Links, News and Resources (1)

These are my links about Repository Pattern: the differences with DAOs (Data Access Objects); examples with NHibernate, Entity Framework; its use in DDD; its relation to IUnitOfWork; discussion about how to query a repository; the influence of Linq/IQueriable in the evolution of this pattern in .NET (LINQ/IQueryable is a missing piece in Java). There are interesting discussions in Spanish, too. I recommend you should translate them.

Repository
http://martinfowler.com/eaaCatalog/repository.html

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

LLBLGenPro, Entity Framework 4.1, and the Repository Pattern
http://www.mattjcowan.com/funcoding/2011/09/25/llblgen-ef-repository-pattern/

HunabKu: LINQ and Repository
http://fabiomaulo.blogspot.com/2009/06/linq-and-repository.html

Revisiting the Repository and Unit of Work Patterns with Entity Framework
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/06/21/revisiting-the-repository-and-unit-of-work-patterns-with-entity-framework.aspx

EFMVC
http://efmvc.codeplex.com/
Demo web app using ASP.NET MVC 3 RTM, Razor, EF Code First and Unity 2.0
Repository Pattern and Unit of Work

Repository is Dead: Long Live Repository
http://codebetter.com/gregyoung/2009/04/23/repository-is-dead-long-live-repository/

Repository is the new Singleton
http://ayende.com/blog/3955/repository-is-the-new-singleton

DDD: The Generic Repository
http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/

The Repository Pattern
http://blogs.hibernatingrhinos.com/nhibernate/archive/0001/01/01/the-repository-pattern.aspx

N-Tiers using POCOs and Entity Framework – Part Two: Model and Entities
http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-2.html

N-Tiers using POCOs and Entity Framework – Part Five: DataAccess Layer
http://blog.jorgef.net/2010/09/n-tiers-pocos-ef-5.html

N-Tiers using POCOs and Entity Framework – Part Six: Source Code
http://blog.jorgef.net/2011/02/n-tiers-pocos-ef-6.html

Using the NHibernate Repository Pattern in C# ASP .NET
http://jasper-net.blogspot.com/2011/04/using-nhibernate-repository-pattern-in.html

Mock a database repository using Moq
http://www.codeproject.com/Articles/47603/Mock-a-database-repository-using-Moq.aspx

The wages of sin: Proper and improper usage of abstracting an OR/M
http://ayende.com/blog/4788/the-wages-of-sin-proper-and-improper-usage-of-abstracting-an-or-m

The wages of sin: Over architecture in the real world
http://ayende.com/blog/4786/the-wages-of-sin-over-architecture-in-the-real-world

Architecting in the pit of doom: The evils of the repository abstraction layer
http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer
Better Domain-Driven Design Implementation
http://www.udidahan.com/2007/03/06/better-domain-driven-design-implementation/

Entities, Services and what goes between them…
http://ayende.com/blog/2145/entities-services-and-what-goes-between-them

Suteki Shop
http://mikehadlow.blogspot.com/search/label/Suteki%20Shop
http://code.google.com/p/sutekishop/
Suteki Shop is an eCommerce application. The orginal aim is to write a site for a fashion retail business. It includes a product catalogue, shopping cart and order processing.
Using
    * .NET 4.0
    * ASP.NET MVC 3
    * MVC Contrib
    * NHibernate
    * Windsor IoC Container

Hunabku
https://bitbucket.org/fabiomaulo/hunabku
Source for @fabiomaulo blog examples
http://www.fabiomaulo.blogspot.com/

Repository, IQueryable y otras hierbas
http://cprieto.com/index.php/2010/05/20/repository-iqueryablet-y-otras-hierbas/
"cuando Fowler y Eric Evans en su libro DDD definieron Repository no existía el concepto de IQueryable y creo que no muchos se lo veían venir, así que simplemente si asociamos que Repository es una abstración superior del acceso a datos y este se debe comportar como una colección en memoria (mezclando las definiciones de Fowler y Evans) y coincidimos en que en la .Net Framework las colecciones pueden extenderse a IQueryable, es fácil razonar que por definición un repositorio finaliza implementando IQueryable<T> (mera jalada mi filosofía y asociación, pero para filósofo preguntémosle mejor a @ajlopez!)" <—Great! @cprieto reads my philosophy posts 😉
Spanish discussion http://groups.google.com/group/altnet-hispano/browse_thread/thread/9c9e84a850dd00bc

HunabKu: Enhanced Query Object
http://fabiomaulo.blogspot.com/2010/07/enhanced-query-object.html

Implementing Repository Pattern With Entity Framework
http://www.codeproject.com/KB/database/ImplRepositoryPatternEF.aspx

Entity Framework as Repository and UnitOfWork?
http://stackoverflow.com/questions/520065/entity-framework-as-repository-and-unitofwork

Repository or DAO?: Repository
http://fabiomaulo.blogspot.com/2009/09/repository-or-dao-repository.html

Repository or DAO?: DAO
http://fabiomaulo.blogspot.com/2009/09/repository-or-dao-dao.html

Repositories for Value Objects?
http://tech.groups.yahoo.com/group/domaindrivendesign/message/17972

How to use dependency injection and the repository pattern with ASP.NET web services?
http://stackoverflow.com/questions/1449870/how-to-use-dependency-injection-and-the-repository-pattern-with-asp-net-web-servi

FubuMVC Contrib
http://code.google.com/p/fubumvc-contrib/
Contrib for FubuMVC a Front Controller-style MVC framework designed primarily for Web applications built on ASP.NET
Many samples with IRepository, NHibernate, IUnitOfWork

MPBlog Implementation. Part 4
http://www.simplyvinay.com/Post/50/MPBlog-Implementation.-Part-4.aspx
NHibernate Repository and Unit Of Work

Linq specifications: from Argentina with Love
http://joseoncode.com/2009/12/24/linq-specifications-from-argentina-with-love/

IRepository interface
http://weblogs.asp.net/alexeyzakharov/archive/2009/11/18/irepository-interface.aspx

nHibernate, Linq and Queries
http://lucisferre.net/2009/05/19/nhibernate-linq-and-queries/

The DAL should go all the way to UI
http://ayende.com/blog/3958/the-dal-should-go-all-the-way-to-ui

Returning IQueryable<T>
http://weblogs.asp.net/fredriknormen/archive/2008/12/01/returning-iqueryable-lt-t-gt.aspx

Generic Repository
http://grepo.codehaus.org/
The Generic Repository (grepo) is an open source (ASLv2) framework for Java which allows you to access (database) repositories in a generic and consistent manner.

The catalogue metaphor and command-query seperation architectures
http://codebetter.com/iancooper/2009/10/08/the-catalogue-metaphor-and-command-query-seperation-architectures/
Query Objects vs Methods on a Repository
http://www.udidahan.com/2007/03/28/query-objects-vs-methods-on-a-repository/

Using Repository and Unit of Work patterns with Entity Framework 4.0
http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

AltNet-Argentina: DAO, Repository y clases Query
http://groups.google.com/group/altnet-argentina/browse_thread/thread/a3f5324ab8418277?pli=1

DDD: The Generic Repository
http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/

My Links
http://www.delicious.com/ajlopez/repository

More links about other patterns are coming.

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

July 26, 2011

Domain-Driven Design: Links, News, Resources (1)

More than four years (!) ago, I wrote down a list of DDD resources:

Domain-Driven Design Resources

Now, it’s time to publish a new (partial) list of resources. First, Wikipedia definition:

Domain-Driven Design
http://en.wikipedia.org/wiki/Domain-driven_design

Domain-driven design (DDD) is an approach to developing software for complex needs by deeply connecting the implementation to an evolving model of the core business concepts.[1] The premise of domain-driven design is the following:

  • Placing the project’s primary focus on the core domain and domain logic
  • Basing complex designs on a model
  • Initiating a creative collaboration between technical and domain experts to iteratively cut ever closer to the conceptual heart of the problem.

Domain-driven design is not a technology or a methodology. DDD provides a structure of practices and terminology for making design decisions that focus and accelerate software projects dealing with complicated domains.

The term was coined by Eric Evans in his book of the same title.[2]

My recent links:

Domain-Driven Design Community
http://domaindrivendesign.org/

Skills Matter : DDD eXchange 2011: Udi Dahan on Domain Model
http://skillsmatter.com/podcast/design-architecture/talk-from-udi-dahan

RESTful SOA or Domain-Driven Design – A Compromise?
http://www.infoq.com/presentations/RESTful-SOA-DDD

Review: Microsoft N Layer App Sample, Part IV-IoC FTW – Ayende @ Rahien
http://ayende.com/blog/29697/review-microsoft-n-layer-app-sample-part-iv-ioc-ftw

Aggregate | Domain-Driven Design Community
http://domaindrivendesign.org/node/88

Services in Domain-Driven Design | Jimmy Bogard’s Blog
http://lostechies.com/jimmybogard/2008/08/21/services-in-domain-driven-design/

Sample Application First Steps
http://thinkddd.com/blog/2009/03/09/sample-application-first-steps/

Composition Patterns « Caminao’s Ways
http://caminao.wordpress.com/how-to-implement-symbolic-representations/patterns/representation-patterns/composition-patterns/

Skills Matter : DDD eXchange 2011: Patrik Fredriksson on DDD
http://skillsmatter.com/podcast/scala/talk-by-patrick-fredriksson

Skills Matter : DDD eXchange 2011 10-06-11
http://skillsmatter.com/event/design-architecture/ddd-exchange-2011

Skills Matter : In The Brain of Greg Young: CQRS, not just f
http://skillsmatter.com/podcast/open-source-dot-net/cqrs-not-just-for-server-systems

Domain Drive Design N-Layered .NET 4.0 Architecture Guide
http://blogs.msdn.com/b/marblogging/archive/2011/05/23/domain-drive-design-n-layered-net-4-0-architecture-guide.aspx

What is Domain Driven Design? – Jak Charlton – Insane World – Devlicio.us – Just the Tasty Bits
http://devlicio.us/blogs/casey/archive/2011/05/16/what-is-domain-driven-design.aspx

Eben Roux | Aggregate Roots vs. Single Responsibility (and other issues)
http://www.ebenroux.co.za/post/2010/07/27/Aggregate-Roots-vs-Single-Responsibility-(and-other-issues).aspx

Eben Roux | DDD != Aggregate Root
http://www.ebenroux.co.za/post/2009/11/24/DDD-!3d-AR.aspx

Eben Roux | Natural Aggregates vs Synthetic Aggregates
http://www.ebenroux.co.za/post/2010/08/20/Natrual-Aggregates-vs-Synthetic-Aggregates.aspx

Coding Instinct: Queries & Aggregates & DDD
http://www.codinginstinct.com/2011/04/queries-aggregates-ddd.html

Repository is Dead: Long Live Repository | Greg Young
http://codebetter.com/gregyoung/2009/04/23/repository-is-dead-long-live-repository/

domaindrivendesign : Message: What is wrong with aggregate roots?
http://tech.groups.yahoo.com/group/domaindrivendesign/message/21445

DDD: Specifications, Language, and Locality | Greg Young
http://codebetter.com/gregyoung/2008/12/21/ddd-specifications-language-and-locality/

Domain Driven Design with Spring and AspectJ – Java Code Geeks
http://www.javacodegeeks.com/2011/02/domain-driven-design-spring-aspectj.html

Objects_of_Value_KevlinHenney.pdf (application/pdf Object)
http://accu.org/content/conf2010/Objects_of_Value_KevlinHenney.pdf

DDDSample.Net
http://dddsamplenet.codeplex.com/

HunabKu: Repository or DAO?: Repository
http://fabiomaulo.blogspot.com/2009/09/repository-or-dao-repository.html

Abacus
http://www.ebenroux.co.za/page/Abacus.aspx
Example: TDD, DDD, CQRS, Service Bus, Dependecy Injection, Logging, HTTP RPC, Data Access Abstraction, Custom ORM, Composite UI

JavATE – Welcome to JavATE The domain driven framework
http://www.javate.amattioli.it/mainsite/description.html

ndddsample – Google Code
http://code.google.com/p/ndddsample/

http://www.qi4j.orghttp://www.qi4j.org
http://www.qi4j.org/

Bastion DDD Java Framework
http://bastionframework.org/

Sharp Architecture – S#arp Architecture
http://wiki.sharparchitecture.net/default.aspx?AspxAutoDetectCookieSupport=1

NerdDinner with Fluent NHibernate Part 1 – The domain model
http://www.bengtbe.com/blog/post/2009/08/10/NerdDinner-with-Fluent-NHibernate-Part-1-The-domain-model.aspx

From CRUD to Domain-Driven Fluency
http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/

Think DDD
http://thinkddd.com/

My links:

http://www.delicious.com/ajlopez/ddd
http://www.delicious.com/ajlopez/ddd+tutorial
http://www.delicious.com/ajlopez/ddd+video
http://www.delicious.com/ajlopez/ddd+example

Keep tuned!

Angel “Java” Lopez
http://www.ajlopez.com
http://twitter.com/ajlopez

September 12, 2008

Layered architecture in Domain-Driven Design

This time, let explore the concepts of a layered architecture, as proposed by Eric Evans in its classic book Domain-Driven Design, Tackling Complexity in the Heart of Software. In the chapter four of the book, Evans presents this diagram:

 

Evans writes:

For a shipping application to support the simple user act of selecting a cargo’s destination from a list of cities, there must be program code that (1) draws a widget on the screen, (2) queries the database for all the possible cities, (3) interprets the user’s input and validates it, (4) associates the selected city with the cargo, and (5) commits the change to the database. All of this code is part of the same program, but only a little of it is related to the business of shipping.

He proposes that the domain model resides in a layer, the Domain Layer. In this way, the domain model is protected from technicalities as concrete persistence implementation, and presentation duties. I like to say that the domain is as an organism, that receives stimula, actions from the outside, and reacts to such commands. The domain should run without detailed knowledge of the rest of the application. Serialization between physical tiers, presentation details and database access, should be clearly separated from the domain implementation.

The layers could be described as:

UI (User Interface): the easiest to understand, this layer is the responsible of displaying information to the user, and accept new data. It could be implemented for web, desktop, or any presentation technology, present or future. For example, it could be a voice application, that interacts with the user via a phone. The acid test for our design is that a radical change in user interface should have minimal (or controled, at least) impact in the rest of the system.

Application Layer: it’s in charge of coordinating the actions to be performed on the domain. There are no business rules or domain knowledge here. No business state resides in this layer. It delegates all domain actions to the domain. It could coordinate many actions (possibly in many domains). It could prepare the infrastructure to be ready to work with the domain for an specific action (for example, preparing transaction scopes).

Domain Layer: In this layer resides the heart of software, according to Evans. Business rules and logic lives inside this layer. Business entity state and behavior is defined and used here. Communication with other systems, persistence details, are forwarded to the infrastruture layer. Evans discuss the patterns he uses in this layer, as Entities, Value Objects, Services, Repositories and Factories. We would explore the patterns and implementations in future posts.

Infrastructure Layer: God and devil are in the details, and in the infrastructure layer. Its main responsability is the persistence of the business state, most frequently, using a relational database.

My idea is to take an example (possibly a domain from Jimmy Nilsson), and develop it using these ideas, showing concrete code in Java and .NET. At some point, I will discuss about code generation from an abstract model, but it will not be the focus of these posts.

Sources:

Domain-Driven Design, Tackling Complexity in the Heart of Software, by Eric Evans.
Applying Domain-Driven Design and Patterns: With Examples in C# and .NET, by Jimmy Nilsson
.NET Domain-Driven Design with C#, Problem, Design, Solution, by Tim McCarthy. (There is a section in Tim’s blog dedicated to this book).

You can download freely

Domain-Driven Design Quickly

from InfoQ.

Angel “Java” Lopez
http://www.ajlopez.com/en

September 1, 2008

The path to Domain Model and Domain-Driven Design

Filed under: Domain-Driven Design, Software Development — ajlopez @ 10:34 am

During years, the software development community have been struggled with complexity and change. Software development is one of the human activities with many level of details: you must grasp the whole picture, and still have to take account of every small detail. A developer or a team of developers have to master lot of concepts, architecture styles, design and implementation patterns, languages, technologies, best practices, and more: they have to exercise soft skills of communications with other stakeholders of the project.

All this could be a daunting task.

Many paradigms emerged last decades, notably the Object Oriented one. But it took many divergent paths: one was the academic purism, with Smalltalkers and related guys, that made a great job spreading the word about objects, but they remain working in some niche apps, not crossing the chasm to take the mainstream of development (I guess the fragmentation of Smalltalk dialects was one of the main reasons that cause that state of affairs in ST community). Don’t misunderstood me: Smalltalk has a strong and live community, but it’s not one of the languages with many enterprise applications to show.

C++ was the first popular language to give “objects to the masses”, but with the emergence of complicated technologies (do you remember the naked Windows API? or any GUI API?), and the explosion of PC market, the mainstream of development was taken by languages like dBase derivatives, Delphi and Visual Basic, the last one having no support to objects until version 3.x, and then, only a limited one. (Visual Basic was a killer to beatiful ideas, like Actor language: an object-oriented, GUIfied Forth extension, implemented in Windows). (Yes, I must take note of COBOL: the language was and still is a main language in many environments).

Java made its appearance at mid 90s, influxing a fresh air (I’ve never programmed with VB 6.0: after meet with Java paradise, I’ve never wanted to fight with Aparment Threading Models and COM stuff). We had a library of classes, true objects, but more: we were blessed by a garbage collector. The new “design patterns” could be adopted in a massively way. Objects began to be everywhere. Frameworks started to emerge.

But something was still missing: altought frameworks took advantage of object ideas, the core business implementation of most application didn’t reflect the new capabilities. The ellusive Domain Model was a “holy grail” that was never easily found. Sun’s J2EE was a mixed failure to make domain models in Java. When .NET was born, Microsoft didn’t repeat the mistake, and in its initial Pattern and Practices papers, they didn’t use any Domain Model ideas (I guess they are still reluctant to adopt Domain Model, Linq To SQL, still are data-oriented beast, Entity Framework is the next hope).

 Java community has a great set of open source tools and libraries, from Ant to Maven to Tomcat. The simplicity of POJO programming (Plain Old Java Objects), joined with non-intrusive persistence solutions (notably Hibernate), gave a new way to reach more clear implementations of a Domain Model.

.NET was a late player in game: more of the tools and examples in .NET world were data-centric or data-oriented, with Datasets and data-binding features in all presentation (WinForms and ASP.NET). .NET community learnt from the Java experience, and in last years, we have Domain Model ideas implemented in the two worlds.

Eric Evans wrote a seminal book about his ideas about Domain-Driven Development, where the Domain Model is not one more artifact, but it’s the heart of the software to develop. He push beyond Domain Model, given guidance of new patterns and ways to implement it. The book explains a process to create and discover a model, with the use of a Ubiquitous Language (shared with users), and how to improve the model along the development process.

Domain model implementations, and DDD, are great topics to cover. I want to start writing about them, discussing many points, and giving concrete examples in Java and .NET. It’s not an easy task, so, don’t expect a daily post: the job will take time.

For now, you can visit my link collection about DDD at:

http://del.icio.us/ajlopez/ddd

Some of my previous posts about DDD:

Mini Book Domain Driven Design Quickly

Domain-Driven Design Resources

Angel “Java” Lopez
http://www.ajlopez.com/en

November 12, 2007

Application Generation using AjGenesis

These days, I wrote new examples for my open source project AjGenesis

http://www.ajlopez.com/ajgenesis
http://www.codeplex.com/ajgenesis

Using AjGenesis, we can produce, starting from our own model, applications for ASP.NET 1.x/2.x, JSP, using SQL Server in .NET, with ADO.NET or NHibernate, or MySql with Java and Hibernate. The sample generated applications use a layered architecture (but remember: these are sample applications, you can write and use your own models, tasks, and templates). Other option: it can generate layers following ideas from Eric Evans’ Domain-Driven Design.

I’m still writing those examples, but now, you can download the current version from

AjGenesisExamples3New.zip

The examples require the use of AjGenesis last release:

AjGenesis Version 0.4.3

but you can try the current version under development:

AjGenesis Version 0.5

In this post, I want to comment how AjGenesis works and some of its inner structure, using one of those examples. Although I will concentrate in producing VB.NET code, you’ll find that the example is able to produce C Sharp and Java/JSP solutions, as well.

First, let’s review first some points about the project. The big picture:

AjGenesis Version 0.4.3 is written using VB.NET V1.x, but version 0.5 is the current version under development, and it was rebuilt using .NET 2.0. The project is open source, and has a BSD-like license, that allows to use it in any project what you want: you only need to comply with the license (in short, put some reference to the original project). It is possible to be used like a library, invoked from your own project, or it is possible to be invoked from command line, or even it can be used from using NAnt (this tool gives you a better organization of the code generation tasks).

There are several samples in the page of the project (inside the project zip source file and in additional files). They generate code from a model, invoking tasks and processing templates. The samples generate code PHP, Java, JSP, VB.NET, C#, ASP.NET, and even scripts of procedure and data base stored. I want to emphasize two points:

The model to use is totally definible by you. It’s a free model, it’s not a fixed one. You can model what you want to model.

– The tasks and templates to apply are totally programmable and controlable. You are in charge. 

That’s make a difference from other generators. We can create our own model, and its own templates and tasks, to generate any text artifacts. Other systems start from the data base, and they only generate a group of predefined text files (as POJOs, plain old java objects, or DAOs, Data Objects Access). But with AjGenesis you can generate any text file you need.

In order to better understandind the free model concept, read a previous post:

Generating Code Hello World with AjGenesis

In that post, the initial steps are described, using a free model, totally oriented to the domain to represent: a typical Hello World application, implemented in different technologies.

Creating an application

Let’s do something more complete in this post. Suppose we need to create a simple solution simple, with two tables, in a MS SQL Server databse, source code in VB.NET 2,0, web interface, layer of services, layer of data, business components and business entities a la Microsoft. We want to generate the solution, the projects, scripts for database creation, and stored procedures. This example is included in the examples AjGenesisExamples3New.zip. First step: to write the model.

The project

In a directory of projects of the examples that accompany this article, there is a Projects/AjFirstExample directory.

In that directory it is the Project.xml file that contains the model.

<Project>
    <Name>AjFirstExample</Name>
    <Description>First Example
    using AjGenesis</Description>
    <Prefix>AjFE</Prefix>
    <Domain>com.ajlopez</Domain>
    <CompanyName>ajlopez</CompanyName>
    <Model>
        <Entities>
            <Entity
            Source="Entities/Customer.xml"/>
            <Entity
            Source="Entities/Supplier.xml"/>
        </Entities>
    </Model>
</Project>

Remember: the model is free. Here we define the templates that we are going to use. The model contains two simple entities: customers and suppliers.

The entities

The XML file is not terribly long: AjGenesis allows that any node of the model is specified apart in a file. This is a criterion that I have used to define how the model is written: the resulting XML does not have to hurt at sight, must be understandable and abarcable in a reading.

In the Project.xml, that feature is used in the case of the entities, with the Source attribute. Let us examine an entity, written in Entities/Customer.xml:

<Entity>
    <Name>Customer</Name>
    <Description>Customer Entity</Description>
    <SetName>Customers</SetName>
    <Descriptor>Customer</Descriptor>
    <SetDescriptor>Customers</SetDescriptor>
    <SqlTable>customers</SqlTable> 

    <Properties> 

        <Property>
            <Name>Id</Name>
            <Type>Id</Type>
        </Property> 

        <Property>
            <Name>Name</Name>
            <Type>Text</Type>
            <SqlType>varchar(200)</SqlType>
        </Property> 

        <Property>
            <Name>Address</Name>
            <Type>Text</Type>
            <SqlType>text</SqlType>
        </Property> 

        <Property>
            <Name>Notes</Name>
            <Type>Text</Type>
            <SqlType>text</SqlType>
        </Property> 

    </Properties>
</Entity> 

There are attributes of the entities, like its name and description, in plural and singular. This data serve to name them in the resulting pages, or within the code. The properties are the fields to maintain in each entity..

Aside from the entities, in another directory, Technologies, specifies the dependent model of the technology, like VbNet2:

The templates

The templates to use are at the Templates/VbNet2 directory:

They are the templates for generation of code VB.Net 2.0. Also we will find groups for C# 1/2, Vb.NET 1,2, Java (although I’m thinking to drop templates for .NET 1.x: I don’t see any reason to maintain these). There are templates to use Nhibernate, Hibernate, JSP, MySql, and concepts of Domain-Driven Design, too. Let’s review a template as an example, the one that generates the organization in Visual BASIC, EntityVb.tpl:

<# 

message "Generating Entity ${Entity.Name}" 

include    "Templates/VbNet2/VbFunctions.tpl" 

include    "Templates/VbNet2/Prologue.tpl"
#> 

'
'    Project ${Project.Name}
'        ${Project.Description}
'    Entity    ${Entity.Name}
'        ${Entity.Description}
'    
'

Public Class ${Entity.Name} 

'    Private Fields

<#
for each Property in Entity.Properties
    message    "Procesando Campo ${Property.Name}"
#>
    Private m${Property.Name} as ${VbType(Property)}
<#
end for
#> 

'    Default Constructor

    Public Sub New()
    End Sub 

'    Public Properties

<#
for each Property in Entity.Properties
    message    "Procesando Propiedad ${Property.Name}"
#>
    Public Property ${Property.Name}() as ${VbType(Property)}
        Get
            Return m${Property.Name}
        End Get
        Set(ByVal Value As ${VbType(Property)})
            m${Property.Name} = Value
        End Set
    End Property
<#
end for
#> 

End Class 

Like before, control structures are used. XML is the serialized format of the model. During the code generation process, the model is loaded in memory, ready to be accesible via dynamic variables.

The steps

We have more files to generate: from the pages ASPX, and their associated code, the projects of facade on watch, organizations, access to data, the file of solution, and more. In order to automate this generation, the example has several files of tasks, in the Tasks directory, where the steps are described to execute. There are two great tasks: the steps to execute independently of the chosen technology, like completing the model, reviewing it, and the employees of the technology, like generating such file JSP or ASPX, depending on if we want Java or .NET.

The task of completing the model is in charge of Tasks\BuildProject.ajg, that begins with:

'
' Build Project
'    Complete the Project Data
'    Project must be loaded in global variable Project
'

PrintLine "Completing Project ${Project.Name}" 

include "Templates/EntityFunctions.tpl"
include "Templates/Utilities.tpl" 

if not Project.Title then
    Project.Title = Project.Name
end if 

if not Project.Version then
    Project.Version = "1.0.*"
end if 

if not Project.SystemName then
    Project.SystemName = Project.Name
end if 

The template includes some auxiliary functions, and then, it begins to complete the model that resides in the Project variable. For example: if the project lacks Project.Title the program set Project.Name as Project.Title. The program continues:

for each Entity in Project.Model.Entities
    PrintLine "Entity " + Entity.Name 

    for each Property in Entity.Properties
        PrintLine "Property " & Property.Name
        if Property.Type="Id" and not Property.SqlType then
            Property.SqlType="int"
        end if
        if Property.SqlType and not Property.SqlColumn then
            Property.SqlColumn = Property.Name
        end if
        if Property.Type="Id" and not Entity.IdProperty then
            Entity.IdProperty = Property
        end if
        if Property.Reference then
...

After that process, the technology tasks are executed. The example use Tasks\BuildVbNet2.ajg, here a fragment:

<# 

include "Templates/Utilities.tpl"
include "Templates/VbNet2/UtilitiesVb.tpl" 

message "Creating Directories..." 

FileManager.CreateDirectory(Project.BuildDir)
FileManager.CreateDirectory("${Project.BuildDir}/Sql")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Entities")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Entities/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Data")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Data/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Services")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Services/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Business")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.Business/My Project")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/App_Themes")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/App_Themes/Default")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/Admin")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/Controls")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebClient/MasterPages")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.WebServices")
FileManager.CreateDirectory("${Project.BuildDir}/Src/${Project.Name}.RemoteServices") 

message "Defining Solution and Projects..." 

...

In this fragment, the directories necessary are created to lodge the solution. The name of the directory is extracted of the model from Project.BuildDir. Note that ${ } in a string is used to expand the inside expression into the string value.

Technology Model

Under the directory Project\AjFirstExample\Technologies they are some models that describes the technology parameters to use:

 

Let’s examine VbNet2.xml:

<Technology>
    <Programming>
        <Dialect>VbNet2</Dialect>
    </Programming>
    <Database>
        <Dialect>MsSql</Dialect>
        <Name>AjFirstExample</Name>
        <Username>sa</Username>
        <Prefix>ajfe_</Prefix>
        <Host>(local)</Host>
    </Database>
</Technology>

These data is used during the template generation phase. It indicates the language, and the database to use.

Generating the solution

We could send the tasks from the command line, but we have a .build file for Nant, one for each technology to generate. We execute the tasks build, buildsql, and deploysql of AjFirstExampleVbNet2.build with the command line:

nant -buildfile:AjFirstExampleVbNet2.build build buildsql

(You must adjust the line

<property name=”ajgenesis.dir” value=”…./AjGenesis-0.5″/>

to reflect your AjGenesis installation directory)

Note the following lines in the build file:

    <target name="loadtasks" description="loads AjGenesis tasks">
        <loadtasks assembly="${nanttasks.dir}/AjGenesis.NAnt.dll" />
    </target> 

    <target name="init" depends="loadtasks" description="init the AjGenesis model, create build directory">
        <mkdir dir="${build.dir}"/>
        <loadmodel model="${project.dir}/Project.xml"/>
        <loadmodel model="${project.dir}/Technologies/${technology}.xml"/>
        <executetask task="${tasks.dir}/BuildProject.ajg"/>
        <executetask task="${tasks.dir}/BuildTechnology.ajg"/>
    </target> 

These tasks load an AjGenesis NAnt tasks, load the models, and execute the tasks.

In the Build/AjFirstExample/VbNet2/Sql directory they are left scripts of creation of the base and stored procedures. And in the directory Src brother, surprise! We’ll have the generated solution:

There were generated several projects, into a solution. We can load the solution into the Visual Studio 2005:

Using another NAnt file, AjFirstExampleCSharp2.build, we can generate the same solution in CSharp:

You will find other projects and examples of .build files, that generate solutions using NHibernate, Hibernate use, JSP, and concepts of Domain-Driven Desing a la Eric Evans.

Reflections

Sure, everything cannot be generated automatically. It is important to remember always that fact. But in the day to day, we recognize that we have amount of repetitive text, tasks that we can well delegate to software.

A key point: the model in AjGenesis is free. The presented examples are only examples: we can general the model that we want, and to write the templates we need. It is important to write the templates so that the generated code is similar to what we had manually generated. If we don’t feel comfortable with the generated code, if it does not have our style, our experience, we’ll end up generating something that we do not understand.

Another thinking: the model must be independent of the technology. In the final example, we have seen how, from the same model, we can generate solutions for VB.NET, CSharp and other technologies.

Software can help us to generate software. More: it MUST help us. Our experience counts: what we learned to make applications, we can overturn it in this species of expert system, code generation tools. In the future, I hope to be able to incorporate to the project, in the templates and tasks, more decision making: as well as we gain experience in writing of applications, we can incorporate our accumulated knowledge on patterns, architecture and styles of programming.

And as it is an open source project, AjGenesis allows us extend it, to our taste and necessity.

Suggestions, use case stories, comments are welcome. You can write as comments to this post, or write directly to me. Thanks to all that tested and adopted this project, and helped me to write it.

Angel “Java” Lopez
http://www.ajlopez.com/en

March 3, 2007

New book on Domain Driven Design

Filed under: .NET, Books, Domain-Driven Design — ajlopez @ 8:51 am

Tim McCarthy is preparing a new book, with code examples (great!) in .NET, implementing the Domain-Driven Design ideas, from Evans et al. The book is for Wrox Press, in the Problem-Design-Solution series; the title will be “”.NET Domain-Driven Design with C#: Problem-Design-Solution”.

It’s great news. We need more implementation examples of DDD ideas. Although DDD has a wide choice of implementations (at high level and details), it will be important the existence of source code and reference implementacion, to the adoption of this kind of solutions.

Meanwhile, you can download some code and slides from Tim presentations:

Talk on Domain Driven Design for the OC C#/VB.NET/Architecture User Groups

Talk on Domain Driven Design for San Diego .NET Developers Group

It’s interesting his implementation of a Composite Specification, and its use in repositories:

A Composite Specification Pattern Implementation in .NET 2.0

Excellent!

Angel “Java” Lopez
http://www.ajlopez.com/en

December 12, 2006

Mini Book Domain Driven Design Quickly

Filed under: Domain-Driven Design — ajlopez @ 7:45 pm

InfoQ has published a mini-book (printed version with cost, free pdf to download), that is a summary of DDD, and of Eric Evan’s book on DDD.

Table of contents

This book is a short, quickly-readable summary and introduction to the fundamentals of DDD; it does not introduce any new concepts; it attempts to concisely summarize the essence of what DDD is, drawing mostly Eric Evans’ book, as well other sources since published such as Jimmy Nilsson’s Applying Domain Driven Design, and various DDD discussion forums.  Chapters of the book include:

  1. Building Domain Knowledge
  2. The Ubiquitous Language
  3. Model Driven Design
  4. Refactoring Toward Deeper Insight
  5. Preserving Model Integrity
  6. Interview with Eric Evans on why DDD matters today

About the book

Domain-Driven Design Quickly was produced by InfoQ.com, summarized primarily by Abel Avram and with Floyd Marinescu as managing editor. Special thanks to Eric Evans for his support and Vladimir Gitlevich and Dan Bergh Johnsson for their detailed reviews. The intention of this book is to get an introduction to Domain-Driven Design into as many hands as possible, to help it become mainstream.

More info on:

http://www.infoq.com/minibooks/domain-driven-design-quickly

I’ve downloaded the .pdf from

Download this book FREE (PDF)

December 11, 2006

Domain-Driven Design Resources

Filed under: Domain-Driven Design — ajlopez @ 9:04 am

July 2011 Update: Domain-Driven Design: Links, News, Resources (1)

I have my links collection on Domain-Driven Design, and I want to post it to this blog. This list is only a disorganized collection but I think that can be useful:

Eric Evans’ Site
http://domaindrivendesign.org

My link collection on Delicious
http://del.icio.us/ajlopez/ddd

Organizing Domain Logic
http://weblogs.asp.net/pgielens/archive/2006/08/08/Organizing-Domain-Logic.aspx

Spring XT
http://springxt.sourceforge.net/index.php/Main_Page

Anemic Domain Model
http://www.martinfowler.com/bliki/AnemicDomainModel.html

Notifications
http://www.martinfowler.com/eaaDev/Notification.html

Fluent Interface
http://www.martinfowler.com/bliki/FluentInterface.html

Specifications
http://www.martinfowler.com/apsupp/spec.pdf
http://www.martinfowler.com/bliki/SpecificationByExample.html
http://sbtourist.blogspot.com/2006/01/case-for-specifications.html
http://sbtourist.blogspot.com/2006/02/another-case-for-specifications.html
http://sbtourist.blogspot.com/2006/05/idea-for-composite-specifications.html
http://sbtourist.blogspot.com/2006/05/implementing-composite-specifications.html
http://www.jeffperrin.com/index.php/2006/06/28/specification-pattern-with-predicates/

You must read all posts from Sergio Bossa
http://sbtourist.blogspot.com
http://del.icio.us/sbtourist/Domain-Driven-Design

Spring Modules XT
https://springmodules.dev.java.net/docs/reference/0.5/html_single/#about

A DDD example in Java
http://www.bettersoftwarefaster.com/
http://www.myjavaserver.com/~bswf/downloads/carserv.zip

Applying the Application Layer in Domain-Driven Design
http://weblogs.asp.net/pgielens/archive/2006/05/31/Applying-the-Application-Layer-in-Domain-Driven-Design.aspx

DDD: Can I drop my Service Layer?
http://peter.jteam.nl/?p=17

Concurrency control in databases: Introduction
http://peter.jteam.nl/?p=8

Peter Veenjter on DDD
http://peter.jteam.nl/?cat=6

Constructing View objects with the Builder pattern
http://sbtourist.blogspot.com/2006/07/constructing-view-objects-with-builder.html

Domain-Driven Design: Model Driven Architecture Done Right?
http://hinchcliffe.org/archive/2005/03/20/189.aspx

A Better Path to Enterprise Architectures
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/sessfin00.asp

Puede ser interesante este articulo de Hibernate con un Modelo de Dominio sencillo
http://www.theserverside.net/tt/articles/showarticle.tss?id=NHibernate

Avoiding Anemic Domain Models with Hibernate
http://wrschneider.blogspot.com/2005/01/avoiding-anemic-domain-models-with.html

What is a View in Domain Driven Design?
http://billhamaker.wordpress.com/2006/08/03/what-is-a-view-in-domain-driven-design/

A Proposal for an Abstract Domain Pattern « Bill Hamaker’s Blog
http://billhamaker.wordpress.com/2006/08/24/a-proposal-for-an-abstract-domain-pattern/

A Repository Example
http://abc.truemesh.com/archives/000464.html

DDD Group Blog
http://blog.gmane.org/gmane.comp.programming.domain-driven-design

Steve Eichert – Domain Driven Design
http://www.emxsoftware.com/Domain+Driven+Design

Hooking your Domain Model and UI Layer
http://www.emxsoftware.com/Domain+Driven+Design/Hooking+your+Domain+Model+and+UI+Layer

Keeping the Domain Model free from Persistence Logic
http://weblogs.asp.net/pgielens/archive/2005/07/29/420995.aspx

DDD: Aggregates & Repositories
http://www.emxsoftware.com/Domain+Driven+Design/DDD+Aggregates++Repositories

How Domain Driven Design changed my way of thinking
http://www.emxsoftware.com/Domain+Driven+Design/How+Domain+Driven+Design+changed+my+way+of+thinking

A quick comparison of Domain Model vs. Manager (Service) Model
http://www.emxsoftware.com/SOA/A+quick+comparison+of+Domain+Model+vs+Manager+Service+Model

Implementing Manager Models with a domain model
http://www.emxsoftware.com/SOA/Implementing+Manager+Models+with+a+domain+model

Vote Manager Model, Domain Model, or Both
http://www.emxsoftware.com/SOA/Vote+Manager+Model+Domain+Model+or+Both

Does SOA require Object-Message mappers It depends
http://weblogs.asp.net/fbouma/archive/2004/03/06/85105.aspx

Domain-Specific Modeling and Model Driven Architecture
http://www.bptrends.com/publicationfiles/01-04%20COL%20Dom%20Spec%20Modeling%20Frankel-Cook.pdf#search=%22domain%20driven%20example%22

Domain driven design implemented in Spring 01
http://forum.springframework.org/showthread.php?t=19429
Domain driven design implemented in Spring 02
http://forum.springframework.org/showthread.php?t=19429&page=2
Domain driven design implemented in Spring 03
http://forum.springframework.org/showthread.php?t=19429&page=3
Domain driven design implemented in Spring 04
http://forum.springframework.org/showthread.php?t=19429&page=4
Domain driven design implemented in Spring 05
http://forum.springframework.org/showthread.php?t=19429&page=5
Domain driven design implemented in Spring 06
http://forum.springframework.org/showthread.php?t=19429&page=6
Domain driven design implemented in Spring 07
http://forum.springframework.org/showthread.php?t=19429&page=7
Domain driven design implemented in Spring 08
http://forum.springframework.org/showthread.php?t=19429&page=8

http://forum.springframework.org/showthread.php?t=19429&page=5

Domain Driven Design vs Data Driven Design — Domain Driven Design
http://vikasnetdev.blogspot.com/2006/07/domain-driven-design-vs-data-driven.html

Domain-Driven Framework Layering in Large Systems
http://www.riehle.org/computer-science/research/2000/cs-2000-gebos.pdf#search=%22domain%20driven%20example%22

Test Driven Development with Domain Driven Design – Part 1
http://donxml.com/allthingstechie/archive/2005/12/15/2348.aspx

Test Driven Development with Domain Driven Design – Part 2
http://donxml.com/allthingstechie/archive/2005/12/18/2361.aspx

Domain-Driven Design, the quest for software perfection
http://coding.mu/index.php/archives/2005/02/11/domain-driven-design-the-ultimate-solution/

Some thoughts about DDD: Introduction
http://peter.jteam.nl/?p=16

DDD: Can I drop my Service Layer? (en Arquitectura)
http://peter.jteam.nl/?p=17

Domain-Driven Design Using Active Record in .NET
http://davidhayden.com/blog/dave/archive/2006/06/21/2995.aspx

Explore model-driven development (MDD) and related approaches: A closer look at model-driven development and other industry initiatives
http://www-128.ibm.com/developerworks/library/ar-mdd3/

RAD That Ain’t Bad: Domain-Driven Development with Trails
http://today.java.net/pub/a/today/2005/06/23/trails.html

Trails and Firebird
http://www.cstengel.de/tutorial/trails_firebird_tutorial/

Trails
https://trails.dev.java.net/

The Development Abstraction Layer
http://www.joelonsoftware.com/printerFriendly/articles/DevelopmentAbstraction.html

Advnace Mocking Scenarios With Active Record (using Rhino Mocks)
http://www.ayende.com/Blog/2006/04/14/AdvnaceMockingScenariosWithActiveRecordUsingRhinoMocks.aspx

Testing ActiveRecord objects
http://www.ayende.com/Blog/2006/04/14/TestingActiveRecordObjects.aspx

ADO.NET Team Blog
http://blogs.msdn.com/adonet/

LINQ to Entities vs. LINQ to SQL – What should I use and when?
http://dotnetaddict.dotnetdevelopersjournal.com/adoef_vs_linqsql.htm

Trouble with Testing “ActiveRecord” objects
http://steve.emxsoftware.com/NET/Trouble+with+Testing+ActiveRecord+objects

Repository vs ActiveRecord
http://geekswithblogs.net/gyoung/archive/2006/04/28/76647.aspx

Repository, the Foundation of Domain Driven Design
http://geekswithblogs.net/gyoung/archive/2006/05/03/77171.aspx

Lecture 23: Domain-Driven Design, Part 1
http://www.cs.colorado.edu/~kena/classes/6448/s05/lectures/lecture23.pdf
Lecture 23: Domain-Driven Design, Part 2
http://www.cs.colorado.edu/~kena/classes/6448/s05/lectures/lecture24.pdf
Lecture 23: Domain-Driven Design, Part 3
http://www.cs.colorado.edu/~kena/classes/6448/s05/lectures/lecture25.pdf
Lecture 23: Domain-Driven Design, Part 4
http://www.cs.colorado.edu/~kena/classes/6448/s05/lectures/lecture26.pdf
Lecture 30: Domain-Driven Design, Part 5 Supple Design
http://www.cs.colorado.edu/~kena/classes/6448/s05/lectures/lecture30.pdf#search=%22domain%20driven%20example%22

Domain-Driven Modeling with Aspects and Ontologies
http://www.st.informatik.tu-darmstadt.de:8080/ecoop2005/maw/acceptedPapers/Hruby.pdf#search=%22domain%20driven%20example%22

An End to End Domain Driven Development Framework
http://www.isis.vanderbilt.edu/publications/archive/Agrawal_A_10_0_2003_An_End_to_.pdf#search=%22domain%20driven%20example%22

Model View Presenter with ASP.NET
http://www.codeproject.com/useritems/ModelViewPresenter.asp#Downloads

Book Review: Applying Domain-Driven Design and Patterns
http://www.aspnetresources.com/blog/applying_ddd_patterns_book_review.aspx

The Vietnam of Computer Science
http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx

Business domain-driven Java class hierarchies for Domino
http://www-128.ibm.com/developerworks/lotus/library/ls-Java_hierarchies/index.html

Applying Domain-Driven Design and Patterns With Examples in C# and .NET
http://codebetter.com/blogs/david.hayden/archive/2006/06/04/146045.aspx

http://www.theserverside.net/tt/books/addisonwesley/DomainDrivenDesign/DomainDrivenDesign.pdf

Next-Generation Data Access: Making the Conceptual Level Real
http://msdn.microsoft.com/vstudio/default.aspx?pull=/library/en-us/dnvs05/html/nxtgenda.asp

ADO.NET Tech Preview: Entity Data Model
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/ADONET_EDM.asp

http://mondragon.angeltowns.net/paradiso/AplicacionesProyectos.html

Object Relational Mapping Resources on
http://www.orm.net
http://sourceforge.net/projects/orm

Conceptual Queries using ConQuer-II
http://www.orm.net/pdf/ER97-final.pdf

ConQuer: a Conceptual Query Language
http://www.orm.net/pdf/ER96.pdf

Conceptual Queries
http://www.orm.net/pdf/ConceptQueries.pdf

Business Rules and Object Role Modeling
http://www.orm.net/pdf/dppd.pdf

Agent Oriented Enterprise Modeling Based on Business Rules
http://www.informatik.tu-cottbus.de/~gwagner/papers/EM-BR.pdf

Dual Schema Problem
http://devhawk.net/2006/03/28/The+Dual+Schema+Problem.aspx

Understanding and Using ValueModels
http://c2.com/ppr/vmodels.html

More Patterns
http://wiki.moredesignpatterns.com

Ezequiel Jadib on NHibernate and DDD
http://ejadib.wordpress.com/2006/11/20/nhibernate-and-domain-driven-design/

Ben Scheirman posts:

A Journey with NHibernate – Part 1
A Journey With NHibernate – Part 2
A Journey With NHibernate (and DDD) – Part 3
A Journey with Domain Driven Design (and NHibernate) – Part 4
A Journey with Domain Driven Design (and NHibernate) – Part 5
A Journey with Domain Driven Design (and NHibernate) – Part 6
A Journey with Domain Driven Design (and NHibernate) – Part 7

Angel “Java” Lopez
http://www.ajlopez.com/en

Blog at WordPress.com.