LA.NET [EN]

S#arpArchive

May 08

The S#arp framework: WCF integration

Posted in S#arp       Comments Off on The S#arp framework: WCF integration

Today we’re going to take a look at the SharpArch.Wcf assembly, which contains several classes that will help use the S#arp framework from within you WCF services. If you’re looking at the source code, you’ll surely notice that it has lots of  classes, many of each are there just for supporting infrastructural WCF code.

We’ll start by looking at the WcfSessionStorage class. This class implements the ISessionStorage interface we’ve met a in a previous post and it relies on the SessionInstanceExtension type for providing the storage used for keeping a valid ISession instance during a request. This type (SessionInstanceExtension) is really simple: it implements the IExtension<T> interface and adds a public read/writer property of type ISession that will  be filled with a valid session for each request.

The SessionInstanceExtension is injected in the “current” context through the custom InstanceCreationInitializer type, which implements the IInstanceContextInitializer interface (you can implement this interface if you’re interested in influencing the resulting InstanceContext that will be used in the current request). It implements the initialize method by adding an instance of type SessionInstanceExtension to the current context’s extensions  collection.

The ISession lifetime is “controlled” (sort of!)  by a custom IDipatchMessageInspector type (DispatchMessageInspector). The AfterMessageinspector is simple: it will just return the current session (NHibernateSession.Current – recall that this feature relies on the WcfSessionStorage  we’ve talked about in the previous paragraph and it will automatically set it up when it’s null). The AfterReceiveRequest is responsible for doing the clean up: if it finds a valid session, it will close it and remove it from the storage (ie, it will set it to null).

This assembly will also add a custom IInstanceProvider type, ServiceLocatorInstanceProvider, which relies on the  ServiceLocator for getting a reference to the service that will handle the current request.

Injecting all these “pieces” is the responsibility of the custom ServiceHost class (that expands the WCF’s ServiceHost type). If you look at the code, you’ll see that it overrides the OnOpening method for adding a custom service behaviour:

protected override void OnOpening() {
            Description.Behaviors.Add(new ServiceBehavior());
            base.OnOpening();
}

ServiceBehaviour will go over each endpoint you’ve set up and it will:

  • set the instance provider to a new instance of type ServiceLocatorInstanceProvider;
  • add the InstanceCreationInitializer to the instance context initializers collection;
  • add the DispatchMessageInspector type to the message inspectors collection.

The only missing peace is the injection of the custom ServiceHost: it’s done through a factory called ServiceHostFactor. The method will expand the ServiceHostFactory and override the CreateServiceHost method in order to return an instance of our custom ServiceHost type.

Now that we understand the infrastructure, we only need to know how to use it. To show what is need, we’re going to take a look at the Northwind sample. As you might expect after the previous description,the only thing we need to do is configure our service so that it is created through our custom service host (which means that we want to replace the default service host factory with the one introduced by the SharpArch.Wcf assembly). This is really easy and you can do it by setting the Factory attribute on the ServiceHost directive:

<%@ ServiceHost Language="C#" Debug="true"
    Service="Northwind.Wcf.TerritoriesWcfService"
    Factory="SharpArch.Wcf.NHibernate.ServiceHostFactory,SharpArch.Wcf" %>

btw, and in case you didn’t notice, the helper classes introduced in the current context by our custom service host allow us to create services without default constructors (notice that the instance provider depends on the ServiceLocator for performing the instantiation of the service). If you look at the TerritoriesWcfService, you’ll notice that it doesn’t have a default constructor:

public class TerritoriesWcfService : ITerritoriesWcfServic    {
        public TerritoriesWcfService(IRepository<Territory> territoryRepository) {
            Check.Require(territoryRepository != null, "territoryRepository may not be null");

            this.territoryRepository = territoryRepository;
        }
   //more code

I’m not sure about you, but I think I’ll really enjoy  this WCF integration stuff!

And that’s all for today. Keep tuned for more!

May 06

The S#arp framework: the SharpModelBinder

Posted in S#arp       Comments Off on The S#arp framework: the SharpModelBinder

In the last post, we’ve looked at several classes that improve the default binding you get in ASP.NET MVC. Today, we’re going to end the Sharparch.Web assembly study and we’ll take a deep look at the SharpModelBinder custom binder. This custom binder performs the following actions on the OnModelUpdated override:

  • starts by removing all errors that aren’t parsing related;
  • then it copies all validation errors exposed by the validated object to the current model state dictionary.

This behavior is slightly different than the one we had with the ValidatableModelBinder we’ve met in a previous post. Besides doing this stuff in the OnModelUpdated override, this custom binder will also retrieve associated one-to-one and one-to-many properties which are associated with other entities. This work is performed on the override of the BindProperty method.

This method starts by checking if the property’s type implements the IEntityTypedId<> interface. When that happens, it will replace the default ValueProviderResult of that type for the custom EntityValueProviderResult and this new custom provider will be used for populating the property with the correct reference.

The EntityValueProviderResult does most of  its work by overriding the ConvertTo method. As you might expect (especially if you’ve been following along), it uses the service locator pattern for getting a reference to the correct repository that is responsible for loading entities of that type.

If you want to use this type, then you can make it the default binder or associate it with a specific type. Making it the default binder is really easy (and probably recommended if you’re using this framework):

ModelBinders.Binders.DefaultBinder = new SharpModelBinder();

And then, you can proceed almost as if you’re using the standard binder. Here’s an example:

public ActionResult DoSomething(SomeObjectWithRelationsToOtherEntities myObject) {
  if (ViewData.ModelState.IsValid ) {
          _rep.SaveOrUpdate(myObject);
          return RedirectToAction("Index");

   }
   return View(myObject);
}

I’m still no sure if I’ll ever use this approach.  I guess that it’s perfect for scenarios where you’re using ORM and are concentrating on relationships, but I’m still unsure of its use in complex domain scenarios – but again, I’m starting to convince myself that probably ORMs and databases aren’t the best place to keep track of my writing transactions!,,)

And that’s it…more to come about this framework in the future. Keep tuned.

May 01

The S#arp framework: wrapping up the SharpArch.Web assembly study

Posted in S#arp       Comments Off on The S#arp framework: wrapping up the SharpArch.Web assembly study

Today we’re going to wrap up the SharpArp.Web assembly study by looking at its area support. This is really going to be a short post because the S#arp framework reuses Phil Haack’s idea from this post and reuses Steve Sanderson’s helpers presented in this second post. They do an excellent work in describing this feature and since there’s really not much I can add to it, I’ll just point you to the previous posts to understand what’s going on and how you can reuse this feature in your apps.

Apr 30

The S#arp framework: adding support to JSON.Net

Posted in S#arp       Comments Off on The S#arp framework: adding support to JSON.Net

Today we’re going to keep looking at the internals of the SharpArch.Web assembly and we’ll take a quick peek at the JsonNetResult class. This is  a custom ActionResult class which you can use if you need to return JSON serialized by the  Json.NET serializer to the client.

As you recall, custom ActionResult classes are supposed to override the ExecuteResult method in order to write the response that is sent back to the client. In this case, the code for that method is really simple: it will start by setting the content type (if none is specified on thee ContentType property, then the default “application/json” will be used), then it adjusts the content encoding (again, only if the property ContentEncoding is not null) and finally, it will serialize the contents of the Data property and write it to the output buffer of the response object. And that sums it up…

In the current release, you’ll have to instantiate it directly since there aren’t any helpers for doing that. If you intend to use this custom ActionResult frequently, then you probably should write a couple of methods for helping you out. If all your classes are inheriting form a base controller, then that would be a good place to put those methods…if you not, then probably you could create a couple of static helper methods like these:

public static class JsonNetHelpers    {
  public static JsonNetResult JsonNet(Object data) {
            return JsonNet(data, null );
  }

  public static JsonNetResult JsonNet( Object data,String contentType ) {
            return JsonNet( data,contentType, null );
  }

  public static JsonNetResult JsonNet( Object data, String contentType, Encoding encoding ) {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = encoding
            };
  }
}

Notice two things about this approach:

  • if you want to set the JsonSerializerSettings, then you’ll need to save the returned ActionResult object (notice that I’m returning a JsonNetResult instance and not the base ActionResult) and access its SerializerSettings property before returning that instace from your action method;
  • I’m not using extension methods here…why? well, because there’s really not much point in adding this method to a controller  since it doesn’t interact with it…

And that’s all for today. Keep tuned for more on the S#arp framework.

Apr 29

Protected: The S#arp framework: The SharpArch.Web assembly – part II

Posted in S#arp       Comments Off on Protected: The S#arp framework: The SharpArch.Web assembly – part II

This content is password protected. To view it please enter your password below:

Apr 27

The S#arp framework: the SharpArch.Web – part I

Posted in S#arp       Comments Off on The S#arp framework: the SharpArch.Web – part I

In this post we’re going to start looking at the goodies available on the SharpArch.Web assembly introduced by the S#arp framework. This assembly contains several helpers which you can reuse in your ASP.NET MVC projects. In this post, we’re concentrating on the WebSessionStorage class.

I’m not sure if you remember it, but we talked about the ISessionStorage a few days ago. As we saw, this interface is used for managing the storage of a session along a specific time. Here’s the interface again, for those that missed the post or don’t remember it:

public interface ISessionStorage {
        ISession Session { get; set; }
}

The WebSessionStorage implements this interface and guarantees that for each request you’ll reuse the same ISession instance across all stages of the ASP.NET pipeline. In other words, it ensures that the recommended session-per-request pattern is applied to all the web requests. As you might expect, the class uses the HttpContext.Items collection for saving the ISession instance that will be reused across the request. It handles the HttpApplication.EndRequest for ensuring proper cleanup of the current session.

Using this class is simple, as you can see from the following snippet copied from the Northwind demo that accompanies the framework:

NHibernateSession.Init(new WebSessionStorage(this),
                           new string[] { Server.MapPath("~/bin/Northwind.Data.dll") },
                           new AutoPersistenceModelGenerator().Generate(),
                           Server.MapPath("~/NHibernate.config"));

As you can see, this type is passed to the NHIbernateSession’s Init method so that it gets used by the other classes that rely on the NHibernateSession.Current property for getting a valid instance of an ISession. Do keep in mind that this code isn’t thread safe and should be called only once during the lifetime of the application.

And that’s it. I guess that there’s not much more we can say about this class. Keep tuned for more on the S#arp framework.

Apr 27

The S#arp framework: the duplicate entity validator

Posted in S#arp       Comments Off on The S#arp framework: the duplicate entity validator

In the last post I promise that we’d talk about the EntityDuplicateChecker and that’s what we’re going to look at today. As we’ll see, this  class is used by the custom NH validators  that you can find in the SharpArch.Core.NHibernateValidator. The EntityDuplicateChecker implements the IEntityDuplicateChecker, which looks like this:

public interface IEntityDuplicateChecker    {
        bool DoesDuplicateExistWithTypedIdOf<IdT>(IEntityWithTypedId<IdT> entity);
}

The EntityDuplicateChecker’s responsibility is to search for an entity with the same business signature as the IEntityWithTypedId instance that was passed in and that has a different Id.The current implementation of this interface is not really complicated since it relies on getting all the properties used in the business signature (which you can get by calling EntityWithTypedId’s GetSignatureProperties method) and adding a restriction for each to the ISession that is used for interacting with the database.

As you might expect (if you’ve been following along), the ISession is obtained by using the NHibernateSession.Current property which we’ve met in one of the latest posts. Now, even though you can use this class directly in your code, the truth is that you’ll probably end up using the custom HasUniqueDomainSignatureAttribute (if you’re using NH Validator for your domain validation, that is). Whenever you need to add a custom NH Validation rule, you need to add (at least) two classes: one new custom attribute and  a new validator class. Let’s start with the custom attribute…

The S#arp framework introduces the HasUniqueDomainSignatureAttribute, which is really simple and looks like this:

[AttributeUsage(AttributeTargets.Class)]
[ValidatorClass(typeof(HasUniqueDomainSignatureValidator))]
public class HasUniqueDomainSignatureAttribute : Attribute, IRuleArgs    {
        public string Message {
            get { return message; }
            set { message = value; }
        }

        private string message = "Provided values matched an existing, duplicate entity";
}

As you can see, the attribute implements the IRuleArgs:

public interface IRuleArgs    {
   string Message { get; set; }
}

This interface’s only objective is to let you get or set the error message that should be shown when there’s an error. Another interesting thing (from the previous snippet) is the use of the ValidatorClassAttribute. This is used to indicate the type of the validator class that is really responsible for performing the validation of that value. In this case,validation is performed by the HasUniqueDomainSignatureValidator class,which implements the mandatory IValidator interface. Here’s the current code for this class:

public class HasUniqueDomainSignatureValidator : NHibernate.Validator.Engine.IValidator    {
        public bool IsValid(object value) {
            IEntityWithTypedId<int> entityToValidate = value as IEntityWithTypedId<int>;
            Check.Require(entityToValidate != null,
                "This validator must be used at the class level of an " +
                "IdomainWithTypedId<int>. The type you provided was " + value.GetType().ToString());

            IEntityDuplicateChecker duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService();
            return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf<int>(entityToValidate);
        }
}

As you can see, the class has only one method which relies on the service locator for getting a  valid instance of the IEntityDuplicateChecker that is responsible for validation. If you look at the source code, you’ll see that there are other pairs attribute/validator for validating specific types of database keys (you have one pair for strings and another for Guids, so use those instead of the general one I’ve shown if you’re using a strings or a Guids for keys).

Don’t forget that to use this custom validation attribute, you need to register the EntityDuplicateChecker with the ServiceLocator. If you don’t, validation won’t work!

And that’s all for today. Keep tuned for more about the S#arp framework.

Apr 26

The S#arp framework: understanding the data assembly

Posted in S#arp       Comments Off on The S#arp framework: understanding the data assembly

After a small detour into the NH Validator framework (and yes, it was really a small detour since we didn’t see how it integrates really well with NH and other frameworks nor how we can create custom validation rules), in this post we’re going back to our study of the S#arp framework. Today, we’re going to take a deep dive into some of the helper classes that are baked into the SharpArch.Data assembly.

We’ll start by looking at the Repository.cs file. This file contains two classes: RepositoryWithTypedId<T, IdT> and Repository<T>. Repository extends RepositoryWithTypedId, specifying IdT as int. As you might expect, RepositoryWithTypedId contains the code that implements IRepositoryWithTypedId interface.

The RepositoryWithTypedId adds a new property to the API implemented from the interface: the Session property. This (read only) property returns a reference to the ISession instance that the remaining methods use to perform their work. The implementation of this property is really simple: it just delegates to the static NHibernateSession.Current property, which is responsible for doing all the work and getting a valid reference to the “current” ISession (we’ll come back to this class in the future).

Once we get a reference to a valid ISession instance (which, as we’ve seen, relies on the NHibernateSession class), implementing the interface methods are fairly simple . The only note I’d like to make here is that the FindOne method will throw (NotUniqueResultException) if it gets more than one hit.

Now let’s proceed and take a look into the (way more interesting) NHibernateSession class. This is a static class which encapsulates everything you need in order to:

  • load the object/table mappings and build a Configuration object (you can do this through the traditional XML files or by using a fluent interface approach)
  • register eventual interceptors (though you probably shouldn’t go this way because listeners are the way to go with NH 2);
  • get a valid ISession instance from a ISessionFactory previously obtained.

In practice, you’re supposed to initialize the NHibernateSession by calling one of the overloads of the Init method (which you should only once,at startup). Then,you can get a valid session by invoking the Current property:

public static ISession Current {
   get {
      ISession session = Storage.Session;
      if (session == null) {
        if (RegisteredInterceptor != null) {
          session = SessionFactory.OpenSession(RegisteredInterceptor);
        }
        else {
                        session = SessionFactory.OpenSession();
        }

        Storage.Session = session;
      }

      return session;
   }
}

As you can see, the class relies on some sort of storage for keeping the created session (notice the use of the Storage static field). Before creating a new ISession instance, the class will always check for a valid instance of that type in that static field. If it finds one, then it will simply reuse it as the “current” ISession instance. This storage is represented by the ISessionStorage interface:

public interface ISessionStorage {
        ISession Session { get; set; }
}

As we’ll see in the future, the S#arp framework introduces one implementation of this interface that lets you use the session-per-request pattern.

The NHibernateRepositoryWithTypedId and NHibernateRepository generic classes expand the previous repository classes and give you much more control over the ISession usage. Before ending, there’s still time to talk about the DbContext class. This class implements the IDbContext interface and relies on the NHibernateSession in order to get a valid ISession instance.

There’s still one important class to cover (EntityDuplicateChecker), but I’ll leave it for another day!

Apr 22

Today we’re going to keep looking at the SharpArch.Core assembly and try to understand its default support for repositories. Before going on, I guess that it’s a good idea to take a detour and talk a little bit about repositories. One of the problems we (developers) face in most applications is that most of the time we’re so worried with infrastructure code that we loose the so needed domain perspective. As we’ve seen in previous posts, we’ll have two basic type of objects: entities and value objects.

I believe that we all agree in that we have two ways of getting a reference to an object (entity or value object): we can create a new instance by invoking its constructor or we can get a reference to an existing one by traversing an association. In this second case, you start by getting a reference to a know object and then you ask it for a reference to the object you’re interested in. Now, this is all good and simple when we think about OO code, but, again, when we start mixing these concepts with database persistency, things become a lot more interesting (or should I say, difficult?).

I guess that we could always let the database leak into our domain and let users execute a queries over it. Unfortunately, this is nor really a good idea since it tends to lead to a shift on focus from domain to data based design (where the database is king). There are also other  problems…for instance, if you have a model where a customer has lots of addresses and these objects are persisted on a database,then what should you do when:

  • a customer is loaded…should you get the customer and his addresses? only the customer?
  • Should we allow isolated loading of address?

As always,the answer to the previous questions depends on the *context*. DDD answers them by introducing aggregates and repositories for giving you access to objects (aggregates) that been persisted in a database (and are in the “middle” of their life cycle).

Today I’m not going to spend a lot  of time talking about aggregates. I’ll just define them as being a cluster of entities and value objects which have a single access point (also known as aggregate root). You should only hold references to this top level entity, though you can pass “transient” references to the inner entities or value objects. By using aggregates, you can easily maintain the consistency between a group of objects (which is one of the problems we face when working with complex domains).

If you understand the concepts presented in the previous paragraph, then it should be obvious that repositories should only work over aggregates! A repository abstracts the database and gives the developer the illusion of working with a collection of aggregates. As you might expect, you can add and remove aggregates from this “pseudo in-memory” collection. They should also give you references to existing objects (that is, objects that are stored in the database). In this case, you’ll probably have several methods which allow you to specify different filters (or you can even use something like Fowler’s Query Object pattern).

After all this, you shouldn’t be surprised to hear that S#arp framework introduces an interface for representing repositories. It’s called IRepositoryWithTypedId<T> and it looks like this:

public interface IRepositoryWithTypedId<T, IdT> {
        T Get(IdT id); 
        IList<T> GetAll(); 
        IList<T> FindAll(IDictionary<string, object> propertyValuePairs); 
        T FindOne(IDictionary<string, object> propertyValuePairs); 
        T SaveOrUpdate(T entity); 
        void Delete(T entity); 
        IDbContext DbContext { get; }
}

As you can see, in this case we need two generic type arguments: one for representing the type of element the repository works with (T) and the other to set the type of the ID field (IdT). Besides the expected methods (Get, GetAll, SaveOrUpdate and Delete, which are self explanatory), there’s also a couple of members which deserve special attention:

  • FindAll receives a dictionary which contains several entries that filter the returned result set. You’re supposed to use the name of a property as the key and its value for specifying the desired values of that property. The method will return all the elements that have those values in the specified properties;
  • FindOne: similar to the previous method, but in this case, it will return a single instance;
  • DbContext gives you a reference to an object that lets you have access to the general database context associated with the current call.

Since you might be a little confused with DbContext (of type IDbContext), here’s the current API of that type:

public interface IDbContext {
        void CommitChanges();
        void BeginTransaction();
        void CommitTransaction();
        void RollbackTransaction();
}

As you can see, this interface encapsulates all the things you generally need to do in order to work with transactions.

There’s also a specific IRepository interface which uses an int for the ID’s type:

public interface IRepository<T> : IRepositoryWithTypedId<T, int> { }

As we’ve seen in a previous post, S#arp is heavily influenced by NHibernate. So, it shouldn’t surprise you to see that there’s a specific interface that gives you access to all the things you’re used to when working with NHibernate:

public interface INHibernateRepositoryWithTypedId<T, IdT> : IRepositoryWithTypedId<T, IdT>    {
        T Get(IdT id, Enums.LockMode lockMode); 
        T Load(IdT id); 
        T Load(IdT id, Enums.LockMode lockMode); 
        IList<T> FindAll(T exampleInstance, params string[] propertiesToExclude); 
        T FindOne(T exampleInstance, params string[] propertiesToExclude); 
        T Save(T entity); 
        T Update(T entity); 
        void Evict(T entity);
}

public interface INHibernateRepository<T> : INHibernateRepositoryWithTypedId<T, int>, IRepository<T> { }

As you can see, the previous repository interface is augmented to give you full control over the things you’re used to setting when working directly over ISession instances.INHibernateRepository is there for the most used scenario: when the Id property is stored as an integer in the database (just like we had with Entity vs EntityWithTypedId for entities).

And that’s it. Keep tuned for more in S#arp

Apr 20

Protected: The S#arp framework: working with entities

Posted in S#arp       Comments Off on Protected: The S#arp framework: working with entities

This content is password protected. To view it please enter your password below:

Apr 19

The S#arp framework: adding validation to your objects

Posted in S#arp       Comments Off on The S#arp framework: adding validation to your objects

Today we’re going to keep looking at the S#arp framework and we’re going to take a look at how we can reuse the classes introduced by the framework to add validation to an object. Before going on, it’s important to keep in mind that validation is a topic which might generate lots of discussion.

For instance, there are lots of people which say that we should never let an object reach an invalid state (a position I’ve been liking a lot lately). Others say that it’s  perfectly OK to let an entity get into an invalid state…But even those that defend that position don’t agree regarding where that validation should take place (many say that the object should be responsible for validation while others say that validation should be performed by other objects). In my opinion, everything depends on the current context…

Having said  that, it’s time to  go back the S#arp framework and see how to add validation to our objects. In the present release, an object signals that it supports validation by implementing the IValidatable interface:

public interface IValidatable {
  bool IsValid();
  ICollection<IValidationResult> ValidationResults();
}

IValidationResult represents information about an error. Currently, this interface looks  like this:

public interface IValidationResult   {
  Type ClassContext { get; } 
  string PropertyName { get; } 
  string Message { get; }
}

ClassContext identifies the type associated to the current validation result. PropertyName identifies the name of the property that hasn’t a valid value and Message will always contain an error message to inform you about the problem. We still need to look at one last interface: the IValidator interface. It looks like this:

public interface IValidator {
  bool IsValid(object value);
  ICollection<IValidationResult> ValidationResultsFor(object value);
}

This interface should be implemented by any object that is responsible for performing validation, ie, it should be implemented by a validator. The current release of the platform relies on these three interfaces for supporting validation. Why such a “complicated” architecture? Well, it will all make sense when we look at the default implementation of these interfaces. However, do keep in mind that the only “real” requisite is that an object that signals its support to validation needs to implement the IValidationResult.

Having said this, lets go on and take a look at the ValidatableObject class. It expands the BaseObject class and implements the IValidatable interface:

[Serializable]
public abstract class ValidatableObject : BaseObject,IValidatable {
       public virtual bool IsValid() {
           return Validator.IsValid(this);
       } 
       public virtual ICollection<IValidationResult> ValidationResults() {
           return Validator.ValidationResultsFor(this);
       } 
       private IValidator Validator {
           get {
               return SafeServiceLocator<IValidator>.GetService();
           }
       }
}

As you can see,the class uses the service locator pattern for getting a reference to the validation service (which implements the IValidator interface). The SafeServiceLocator performs its work by using the common service locator class but wraps its exceptions in new ones with more better error messages.

The default implementation of the IValidator interface relies on the ValidatorEngine introduced by the NH Validator framework. I’m not a user of this framework, so I’ll create my own implementation of IValidator interface to show you how you can reuse the ValidatableObject class with a custom implementation of a  validation engine.

[Before going, it’s important to notice that if you’re not using an IoC then you should probably bypass this class and implement the interface directly]

Let’s get started…we’ll change our last example in order to illustrate validation and we’re going to create a validator class for our SimpleAddress class. The first thing we need to do is to implement the IValidationResult interface to encapsulate error messages. The current implementation of this interface was built to encapsulate the error messages fired  by the NH Validator engine, so we  won’t be reusing this. We don’t need anything fancy, so this simple class will do it:

public class CustomError:IValidationResult {
  private static readonly Type _customType = typeof( SimpleAddress );
  private readonly String _propName;
  private readonly String _message; 
  public CustomError(String propName, String message) {
      _propName = propName;
      _message = message;
  }
  public Type ClassContext {
            get { return _customType; }
  } 
  public string PropertyName {
            get { return _propName; }
  } 
  public string Message {
            get { return _message; }
  }
}

Now that we have something to encapsulate return error info, we can proceed and implement the SimpleAddressValidator class:

public class SimpleAddressValidator:IValidator {
   public bool IsValid( object value ) {
            var address = value as SimpleAddress;
            if( address == null)
            {
                throw new NotSupportedException();
            }
            return ( String.IsNullOrEmpty( address.Street ) )
                           ? false
                           : true;
  }
  public ICollection<IValidationResult> ValidationResultsFor( object value ) {
            var errors = new Collection<IValidationResult>();
            var address = value as SimpleAddress;
        &
#160;   if( address == null ) {
                throw new NotSupportedException();
            }
            if( String.IsNullOrEmpty( address.Street )) {
                errors.Add( new CustomError( "Street",
                                           "Street must have a valid value" ) );
            }
            return errors;
  }
}

The first thing we do is convert the value parameter into the expected type: when that operation fails, we simply throw a not supported exception. The only rule we have is that Address cannot be null!

Now, we can simply adapt the SimpleAddress class presented  earlier to reuse the ValidatableObject class:

public class SimpleAddress:ValidatableObject {
  public String Street { get; set; }
  public String ZipCode { get; set; }

  protected override IEnumerable<PropertyInfo> GetTypeSpecificSignatureProperties( ) {
            return typeof( SimpleAddress ).GetProperties();
        }
}

We’re still missing one step to make everything work: we need to create a custom service locator. Since this is just demo code, we’re adding the simplest service locator we can create (we’re not performing any error validations and we’re only implementing the IServiceLocator’s GetService method):

public class MyServiceLocator:IServiceLocator {
    public object GetService( Type serviceType ) {
       return new SimpleAddressValidator();
    }
   //all other methods throw NotImplementedException
}

The final step: configure the ServiceLocator to use our service locator. Here’s the final code that does that and sets up everything for testing purposes:

var address1 = new SimpleAddress {
                                       Street = "Street X",
                                       ZipCode = "SomethingElse"
};

var address3 = new SimpleAddress {
                                       Street = "",
                                       ZipCode = "DifferentAddress"
};

ServiceLocator.SetLocatorProvider( () => new MyServiceLocator() );
Console.WriteLine( "address 1 is valid: {0}", address1.IsValid());
Console.WriteLine( "address 3 is valid: {0}", address3.IsValid());

As I’ve said, if you’re using the NH Validator framework, then you should reuse the default implementations of these interface because that will really make all this work we’ve done unnecessary. The SharpArch.Core.NHibernateValidator assembly adds a default validator (Validator) and a default IValidationResult implementation (ValidationResult). As I’ve said, if you’re using the NH Validator framework, then you’ll only need to decorate the properties with the correct  attributes. We’ll come back to this topic on the future, when we take a deep look at the demo projects that accompany the framework.

And that’s it for today…Keep tuned for more on the S#arp framework.

Apr 18

The S#arp framework: using value objects

Posted in S#arp       Comments Off on The S#arp framework: using value objects

If you’ve been involved with DDD, you have surely built several value objects. But what is a value object? Eric Evans defines it (in his seminal work) as being an object which doesn’t have a conceptual identity and that is used for describing a characteristic of a thing. As always, there really isn’t any good rule for identifying value objects since it all depends on the *context* (some objects will be value objects in a context and entities in another).

In practice, value objects are immutable. This means that you’ll end up with objects that need to receive all the necessary values during construction time. If you need to change any of those values, then you’ll need to create a new instance since these objects don’t expose any public setters. Typically, you’ll also want to customize operators == and !=. The S#arp framework introduces a class that takes care of all this boilerplate code. We’re talking about the ValueObject class.

This class extends the BaseObject class and implements the GetTypeSpecificSignatureProperties in a very similar way to what we did in the previous post (the difference is that it ensures that none of the properties are annotated with the DomainSignatureAttribute attribute– more about this in the future). Besides introducing a default implementation for the previous method, it will also introduce custom implementations of the == and != operators (which end up delegating to the Equals method inherited from the base class).

To illustrate the usage of this class, we’ll change the example presented in the previous post and implement SimpleAddress as a value object. Here’s the changes we need to make to the SimpleAddress class:

public class SimpleAddress:ValueObject {   
   public SimpleAddress(String street, String zipCode) {
            Street = street;
            ZipCode = zipCode;
   }
   public String Street { get; private set; }
   public String ZipCode { get; private set; }
}

And that’s it. The changes were minimum and most (if not all) of them are needed to ensure proper immutability. Notice that ensuring immutability of the properties used on the hash calculation is a must for ensuring the correct behavior of our objects (especially if they’re kept on hash tables collections).

And that’s it for today. More about the S#arp framework on the next posts.

Apr 18

The S#arp framework: getting started

Posted in S#arp       Comments Off on The S#arp framework: getting started

This marks the beginning of a new series. I’ve already written about it in the past, but I thought that now would be a good idea to go back and take a deep dive on the existing code. What is the S#arp? Here’s the official definition: “Pronounced "Sharp Architecture," this is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate.”

As you can see, it focus on two areas which are dear to my heart: DDD and NHibernate. As we’ll see along this series, this framework will surely help you, especially if you’re building MVC applications and you’d like to apply some of the concepts defined by DDD. Our study of this framework will start in the base SharpArch.Core assembly and today we’re taking a close look at the abstract BaseObject class.

The BaseObject class is one of the base classes that is reused by other classes. As we’ll see, its main objective is to test for equality between two BaseObjects instances (ie, override the default implementation of the Equals method) and to correctly implement the GetHashCode method.

The first thing you’ll notice about this class is that it’s serializable (ie, it’s annotated with the SerializeAttribute attribute) and that it can be converted (or serialized)  into JSON by using the JSON.NET framework. This might throw you off at first, but it is needed if you’re reusing your domain objects through several layers/contexts (which is something I’ve been staying away for months now – honestly, I’m really convinced that I’d have more hair if I had started doing this earlier, but we’ll leave that talk to another day).

As I said,one of the main purposes of this class is to implement equality. It does that by overriding the the Equals method and performs several steps:

  • first,the received object is “casted” to BaseObject by using the as operator;
  • a reference check is performed: if both objects point to the same memory location, true is immediately returned;
  • if that isn’t the case, then equality depends on a last test which involves comparing the current types and seeing if the object received by method and “casted” to BaseObject is not null and has the same business signature as the current object.

The concept of business signature is fairly important. You can see it as something that uniquely identifies your object. For now, that is all we’ll say about it because uniquely identifying an object depends on the fact you’re using a value object or an entity (DDD concepts which we’ll explore in the future).

Business signatures comparison is performed by the HasSameObjectSignatureAs method. It’s really a simple method which tries to get a list of PropertyInfo objects that represent the current business signature of the type and checks for equality between the values of each property in that list (between the BaseObject instances that are being compared). Obtaining the list of properties is a simple process that ends up calling the abstract GetTypeSpecificSignatureProperties method. If you’re a pattern guy, then you’ll probably recognize the template method pattern here, where a specific step of an algorithm is implemented in a more derived class.

Calculating the hash code depends (also) in the business properties. When there are business signature properties, the GetHashCode returns a hash based on the current type’s hash code and on the hash of the each property (affected by a specific constant). When there aren’t any, it will simply reuse the base Object’s GetHashCode method for getting the hash.

Now that we’ve seen the internals, it’s time to see how we can reuse the class in our code. Even though you won’t be using this class often (the future posts we’ll present other more interesting  classes), I believe that it’s interesting to present a simple example of its usage. Here’s a very simple class which will reuse the BaseObject class to get the correct behavior for equality:

public class SimpleAddress:BaseObject {
  public String Street { get; set; }
  public String ZipCode { get; set; } 
  protected override IEnumerable<PropertyInfo> GetTypeSpecificSignatureProperties( ) {
            return GetType().GetProperties();
        }
}

As you can see, we’re using all the public properties for the business signature of this class (in fact, we could probably represent this class a a value object!). In practice, this means that 2 instances of this type are equal when the values of both properties are equal. It’s important to mention that the base class caches the properties so you don’t need to worry with that.

Now, try running the following code:

var address1 = new SimpleAddress {
                                      Street = "Street X",
                                      ZipCode = "SomethingElse"
                              };
var address2 = new SimpleAddress {
                                      Street = "Street X",
                                      ZipCode = "SomethingElse"
                              };
var address3 = new SimpleAddress {
                                      Street = "Street X",
                                      ZipCode = "DifferentAddress"
                              };
Console.WriteLine( "address1 == address2 : {0}", address1.Equals( address2));
Console.WriteLine( "address1 == address3 : {0}", address1.Equals(address3));
Console.WriteLine("Hash codes:");
Console.WriteLine( "address1: {0} naddress2: {1} naddress3: {2}",
     address1.GetHashCode(), address2.GetHashCode(), address3.GetHashCode() );

If everything goes well, then you’ll see that address 1 equals address 2 and that both of them are different from address3.

Notice that by reusing y
ou only need to indicate the properties that should be used for equality comparisons. This is great because the base class already takes care of several small details that do matter (believe me: implementing a good hash algorithm and equality are more difficult than it might appear at first sight).

And that’s it for today. Keep tuned for more on the S#arp framework.

Jan 20

S#arp 1.0 beta is out

Posted in C#, S#arp       Comments Off on S#arp 1.0 beta is out

Go get it here.

Dec 08

One of the open source projects I’ve been following in these last months is the S#arp project (pronounced Sharp Architecture) started and coordinated by Billy McCafferty. According to the homepage, this framework “is a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate”.  The framework adheres to the following principles (again, taken from their homepage):

  • Focused on Domain Driven Design
  • Loosely Coupled
  • Preconfigured Infrastructure
  • Open Ended Presentation

The current release (which is stable) introduces several reusable assemblies with many classes and interfaces that can be reused in your apps. You’ll also find some samples that show how to use the framework and a VS template that will automatically build you a solution with everything set up for using this framework in your apps! As you can see, there’s already lots of stuff to look at. Today, I’ll concentrate on the SharpArch.Core assembly (to me, this is probably the most important project).

In this project, you’ll find several interfaces and base classes for your domain objects. Lets start with the interfaces…

The IPersistentObjectWithTypeId is the base interface for database interaction. It looks like this:

public interface IPersistentObjectWithTypedId<IdT> {
        IdT ID { get; }
        bool IsTransient();
}

As you can see, it’s a generic interface which only introduces the ID (mapped to your ID on the database table) and a method which indicates if the current object is transient (a transient object is an object which hasn’t still been persisted on the database). As we’ll see, you don’t really have to implement this interface; instead, you can inherit from one of the base classes that already do all that work for you (this is the recommended approach, because those base classes already do some extra work which might be hard to get done right). More about this on the next paragraphs…

The IHasAssignedId generic interface is there for letting you set the ID of a domain object. It has only one method: SetAssignedIdTo. Here’s its signature:

public interface IHasAssignedId<IdT> {
        void SetAssignedIdTo(IdT assignedId);
}

Your objects will have to implement this interface if you want to explicitly set the ID of your object (at least, that’s the idea).

There’s also a IRepository interface which extends the IRepositoryWithTypeId interface by setting the ID type to an integer (System.Int32). Here are their signatures:

public interface IRepository<T> : IRepositoryWithTypedId<T,int> { } public interface IRepositoryWithTypedId<T,IdT>    {
     T Get(IdT id);      
     List<T> GetAll();
     List<T> GetByProperties(IDictionary<string, object>
                           propertyValuePairs); 
     T GetUniqueByProperties(IDictionary<string, object>
                                             propertyValuePairs); 
     T SaveOrUpdate(T entity); 
     void Delete(T entity);

     IDbContext DbContext { get; }
}

As you can see, IRepositoryWithTypeId defines the public methods that the repositories will implement. To be honest, I’m not really a fan of having the GetByProperties, GetUniqueByProperties and GetAll methods on this interface since I’d really prefer to have a separate context for querying (ie, I’d like to maintain my domain model as a transactional/write model).

There are also more specifics NHibernate interfaces, appropriately called INHibernateRepository and INHibernateRepositoryWithTypeId. This last interface extends the IRepositoryWithTypeId interface with several methods which let you interact explicitly with the NH API:

public interface INHibernateRepositoryWithTypedId<T, IdT> :
                IRepositoryWithTypedId<T, IdT>    {
    T Get(IdT id, Enums.LockMode lockMode); 
    T Load(IdT id); 
    T Load(IdT id, Enums.LockMode lockMode); 
    List<T> GetByExample(T exampleInstance, params string[] propertiesToExclude); 
    T GetUniqueByExample(T exampleInstance, params string[] propertiesToExclude);

      T Save(T entity); 
      T Update(T entity); 
      void Evict(T entity);
}

If it depended on me, and since the framework has a DDD focus, I wouldn’t add these interfaces to the core project.

There’s also one more thing that keeps bothering me when I look at these interfaces: the List<T> types that are returned from the GetXXX methods. I don’t really like it and I have changed my customized version of the assembly so that all those members return an IEnumerable<T> instead (just think about it: why do we need List<T> when we aren’t really allowed to add elements to those collections? And even if we needed to to that, wouldn’t it be better to return ICollection<T> or IList<T>?).

Before delving into the classes, I’d like to mention the IDomainObject interface:

public interface IDomainObject {
        bool IsValid();
        InvalidValue[] ValidationMessages { get; }
}

This interface lets you check for validity. Unfortunately, it’s tied up with the NHibernate Validator framework and, again, this is something that I don’t really like. I’d really prefer to have a validation framework based on the concept of domain rule, but this is what we have and we’ll have to live with it…

Now, the main thing you’ll get from the SharpArch.Core assembly are the classes that implement the previous interfaces and that you can reuse in your code. With these classes you’ll automatically get code for checking for equality and code that implements the hash code in a correct way (do notice that implementing the GetHashCode method is really hard work!). We’ll start with the DomainObject class. This class implements the IDomainObject interface and overrides the Equal and GetHashCode methods inherited from the System.Object class.

Before looking at the code, we need to understand the concept of Domain Signature. The domain signature is a value (or combination of values) that doesn’t change during the lifetime of a domain object and that uniquely identify an object (do notice that domain objects do have longer lifetimes than “programming” objects). Do notice that domain signatures aren’t good database keys !

SharpArch introduces the DomainSignatureAttribute for annotating properties of classes that are used in its domain signature. The DomainObject class will look at these attributes when it needs to check fo
r equality or to calculate the hash code of an object. For instance, lets assume that you have a Person class where you’ve reached the conclusion that each instance is uniquely identified by its name (this is just an example!). Here’s how you’d write the code when you’re reusing this framework:

class Person:DomainObject{
   public Person(String name){
      Name = name;
   }
   [DomainSignature]
   public String Name{ get; private set; }
}

As you can see, you just need to annotate the property (or properties) that define the domain signature with the attribute and the base class will automatically add code for checking for equality and for calculating the hash code. Lets start by looking at the code used for checking for equality (defined by the DomainObject class):

public override bool Equals(object obj) {
            IDomainObject compareTo = obj as IDomainObject;

            if (ReferenceEquals(this, compareTo))
                return true;

            return compareTo != null && GetType().Equals(compareTo.GetType()) &&
                HasSameDomainObjectSignatureAs(compareTo);
}

Several interesting things are happening here. First, the method uses the static Object.ReferenceEquals to see if we’re comparing two objects that point to the same object reference. When that doesn’t happen, the method sees if the object that has been passed implements the IDomainObject interface (personally, I’d prefer that it would check for DomainObject instead of the interface, but…) and if it does (and if the object has the same type as the current instance over which the Equals method is called), it’ll will defer the equality calculation to the helper HasSomeDomainObjectSignatureAs method.

protected virtual bool HasSameDomainObjectSignatureAs(IDomainObject compareTo) {
    foreach (PropertyInfo property in DomainSignatureProperties) {
      object valueOfThisObject = property.GetValue(this, null);
      object valueToCompareTo = property.GetValue(compareTo, null);

      if (valueOfThisObject == null && valueToCompareTo == null)
                    continue;

      if ((valueOfThisObject == null ^ valueToCompareTo == null) ||
         (!valueOfThisObject.Equals(valueToCompareTo))) {
                    return false;
       }
   }

   return DomainSignatureProperties.Any() || base.Equals(compareTo);
}

As you can see, equality is calculated by checking the properties annotated with the DomainSignatureAttribute (the DomainSignatureProperties uses LINQ to get the collection of PropertyInfo objects for the properties annotated with the DomainSignatureAttribute). Notice that we can get to the last line of the method in two cases: when there aren’t any properties signed with the DomainSignatureAttribute or when there are and their values match. In the first scenario, we simply redirect to the base class (System.Object) and will let it do its work. In the latter, we’ll just return true (notice the clever use of the Enumerable.Any extension method on the last line of the Equals method).

The GetHashCode method follows the same principles introduced by the Equals method: use the domain signature properties and redirect to the base whenever there aren’t any properties annotated with DomainSignatureAttribute. The method will also use the type and a random number for making sure that you get a good hash code.

public override int GetHashCode() {
    unchecked {
        int hashCode = GetType().GetHashCode();

        foreach (PropertyInfo property in DomainSignatureProperties) {
          object value = property.GetValue(this, null); 
          if (value != null)
             hashCode = (hashCode * RANDOM_PRIME_NUMBER) ^
                                 value.GetHashCode();
         }

         if (DomainSignatureProperties.Any())
                    return hashCode;

         return base.GetHashCode();
   }
}

One thing you might be tempted to do is using the hash for checking for equality. Don’t do that! The only guarantee that hash codes give you is that the equal instances will return the same hash code. It doesn’t say anything about different instances. In practice, you might have two different instances produce the same hash code and that’s ok (really!)

Since the DomainObject class implements the IDomainObject interface, it will also add code for checking for the validity of an object. Currently, these checks are performed by the NHibernator Validator. So, if you’re a fan, reusing this class as a base will let you use their attributes for validation…

The last important class introduced by the core assembly is the PersistentObjectWithTypeId class (there’s also a PersistentObject  class that inherits from the previous class and sets the TypeId to System.Int32). The class expands the DomainObject class and implements the IPersistendObjectWithTypeId interface that was presented earlier.

The most important thing the class does is override the Equals method. Here’s the code:

public override bool Equals(object obj) {
   PersistentObjectWithTypedId<IdT> compareTo = obj as PersistentObjectWithTypedId<IdT>;

   if (ReferenceEquals(this, compareTo))
                return true;

   if (compareTo == null || !GetType().Equals(compareTo.GetType()))
                return false;

   if (HasSameNonDefaultIdAs(compareTo))
                return true;

   return IsTransient() && compareTo.IsTransient() &&
                HasSameDomainObjectSignatureAs(compareTo);
}

As you can see, if we’re talking about non transient objects of the same type, then equality will be performed by checking the value of the ID property (remember that this ID is the one that is used as a primary key on the database table). Domain signature comparison will only be used if both of the objects are transient (if only one of them is transient, then the instances are different).

As you ca
n see, the framework introduces two important base classes: DomainObject and PersistentObject. If you’re doing DDD, then I recommend that you use the DomainObject class, especially if you’re following the domain signature concept. If you’re also using NHibernate, then do reuse the PersistentObject(XXX) class.

As you can see, the S#arp Architecture project is still young, but it’s also interesting and it might be a good framework for supporting your code. I’m already using several of its ideas (not all, because I still don’t agree with some of the options that have been taken) and I’ve been pleased with the overall results.

In the next posts I’ll dig into the repository implementation code.