Archives

Archives / 2010 / January
  • Aspen – part 7 of X – Entity Validations

    Dag König and I had a meeting today about the Aspen project. We talked most of the time about validations and how we should implement it. I decided to post about the current decision made.

    Validation on Entity level


    Sometimes it feels important to add validation to an entity, for example a FirstName can’t have a size greater than X characters etc. But is it important? The main reason why such validation may be of interest is based on the limitation set on the data source. The column FirstName in the database is set to nvarhcar(XX). But should we really add a validation like the following to the entity because of that?

    public class Member
    {
        private string _firstName;
            
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if (string.IsNullOrEmpty(value))
                     throw new ArgumentNullException("FirstName");
    
                 if (value.Length > 20)
                     throw new ArgumentOutOfRangeException("FirstName", 
                                      "FirstName can not have more than 20 chars");
    
                  _firstName = value;
             }
        }
    }

    In real life a company will probably not lose any business because of the length of the FirstName, so the domain model in that case shouldn’t really care about doing the validation, or?! The only reason the validation is there now is because of the constraint added to the data source, but it’s not a constraint for the business. In this case I think that kind of length validation is not important to have in the entity at all, it’s irrelevant for the business. I prefer to not have that kind of logic into my entities, instead I will let the data source throw an exception if the chars exceeds XX numbers of chars. In this case the data source will do the validation. Some of you may say “But by adding the validation to the entity, there will not be any database access, and that will increase performance”. That is true. But how often will the FirstName really exceed the XX numbers of chars? If we use a sophisticated ORM, we can also specify in the mapping between the domain model and database schema, the length of the field etc, and let the ORM do the validation before it tries to persist the model. nHibernate will do it for us, but I haven’t seen a way of doing it with Entity Framework 4 code-only and I’m against adding attributes to my entities. Will not make them a pure POCO. One benefit by adding validation to the entity, would be to prevent a developers for using the entity in a wrong way. He/she will be notified early if the FirstName exceeds 20 chars. But I don’t think it’s up to the domain model to care about performing validation based on a data source constraint.

    I will only add the above validation if that is really a business rule.


    Note: The empty string validation in the code is important, if we don’t have a FirstName we can lose business.

    Should we always let the database handle the validation based on exceptions?

    If we skip the length validation in our FirstName property, the validation will take place by the database. It will throw an exception if the FirstName exceeds the length of the specified ncharchar(XX). So stupid, why should we do the data access in the first place and waste some resources others action can use instead? The answer is, we can do the validation, but not on the entity level, more about that later under the topic “User Interface Validation”. If we use a sophisticated ORM, we can let it perform a validation before the entity is persisted.


    Rule based validation

    There can be a problem by adding validations to the entity or even to other parts of the domain model, for example to the Repositories. Some specific validations can be based on a specific business case or the context the entity is in. If we add validation to the entity, the validation will always take place but in one specific context that kind of validation isn’t important and can stop us for performing a specific business case. So instead of adding validations to the Entity, we perform validations based on the context the entity is in. The validation can for example take place in service/application layer. This can be done in several ways, for example in a simple method where the method will validate the entity’s values. This is the approach we are going to use. The following methods will do different kind of validations of the member entity based on its context.

    ValidateMemberBeforeRegisterTheMember(member);
    
    ValidateMemberBeforeUpdatingTheMember(member);



    User Interface Validation


    WCF RIA Services supports annotation validations, so we can on our DTO for example add validation attributes to properties. WCF RIA Services together with Silverlight binding validation can perform validations on the client-side, WCF RIA Services will also do the validation on the server-side. So instead of adding validation such as length validations to an entity, it can instead be added to the Presentation layer and the Service layer. The following is an example where the WCF RIA Services annotation validation is used:

    public class MemberDto
    {
        [Key]
        public int ID { get; set; }
    
        [Required]
        [StringLength(20)]
        public string FirstName { get; set; }
    
        ...
    }


    Is someone succeeds to by pass the DomainService and try to add entity, the database will throw an exception if the length of the the FirstName exceeds for example 20 chars. How often will that happen. Well probably never, and if it does, the database will to the last validation.

    Based on our business case, we decide to not add length or other kind of constraints for our entities. I would really like to have your comments about this and what solution you prefer to use.



    If you want to know when I add a new blog post, please follow me on twitter: http://www.twitter.com/fredrikn

    Read more...

  • Aspen – part 6 of X – Reusing ObjectContex among Repositories during a DomainSerivce operation.

    (I had to shorten the title down a bit ;))

    I promised to write about how I have implemented the solution mentioned in my previous post and I’m going to keep my promise. But I will not use this solution in the Aspen project, more about that in the end of the post (under the topic “What will I use in the Aspen Project”).

    I will first start with the following code (From my DomainService):

    [Invoke]
    public void Save()
    {
         using (var trans = new TransactionScope())
         {
              _memberRepository.Add(new Member() { FirstName = "Ove", LastName = "Bengt" });
              _gatheringRepository.Add(new Member() { FirstName = "OveG", LastName = "BengtG" });
              trans.Complete();
          }
    }

    By default when we call the TransactionScope Complete method, the Entity Framework ObjectContext inside of the transaction scope will not save any changes. If we use nHibernate within a Transaction scope, it will Flush when we make a call to the Complete method. So what I did was to try to implement a way to let the Complete method call the ObjectContext’s SaveChanges method. If we want to get notified when the Complete method of a transaction is called we can implement the IEnlistmentNofication interface. The interface has several methods, Prepare, Rollback, InDoubt and Commit. Within the Commit we can for example call the ObjectContext’s SaveChanges method:

    public class ObjectContextEnlistment : IEnlistmentNotification
    {
         private readonly IObjectContext _objectContext;
         private PreparingEnlistment _preparingEnlistment;
    
         public ObjectContextEnlistment(IObjectContext ojbectContext)
         {
            if (ojbectContext == null)
                 throw new ArgumentNullException("ojbectContext");
    
            _objectContext = ojbectContext;
         }
    
         public void Prepare(PreparingEnlistment preparingEnlistment)
         {
             _preparingEnlistment = preparingEnlistment;
             _preparingEnlistment.Prepared();
         }
    
         public void Commit(Enlistment enlistment)
         {
             _objectContext.SaveChanges();
             enlistment.Done();
         }
            
         public void Rollback(Enlistment enlistment)
         {
             enlistment.Done();
         }
    
         public void InDoubt(Enlistment enlistment)
         {
             enlistment.Done();
         }
    }

    Note: The above code may not be perfect and solve all kind of EF scenarios etc, I only used it for testing purpose.

    We have to register this IEnlistmentNotification to the transaction so we can be notified. This is done by using the Current running transactions EnlistVolatile method:

    if (Transaction.Current != null)
        Transaction.Current.EnlistVolatile(
                     new ObjectContextEnlistment(_objectContext), EnlistmentOptions.None);

    I will not use this solution in the Aspen project, It was just a fun thing to do.

    In my previous post I also mentioned that I could now reuse an ObjectContext among several Repositories in one Domain Service Operation to reuse the Unity of Work and Identity Map etc, and also automatically dispose the ObjectContext after the operation is completed. lets see how I implemented the solution. Because RIA Services uses WCF, we can get access to the WCF OperationContext. The OperationContext will live during an operation add we can add objects to it. I decided to add the ObjectContext to the OperationContext so every Repository inside a WCF operation will get access to the same ObjectContext from the OperationContext. In Part 3 I wrote about the Repository implementation and also about my IObjectContext interface. Repositories will take an IObjectContext when it’s created. The Repository will then use this interface to get access to an ObjectContext.

    I made some changes since the Part 3 implementation. Now I have a generic BaseRepository<TEntity>. Here is the code for the BaseRepository<TEntity>:

    public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        readonly IObjectContext _objectContext = null;
        readonly IObjectSet<TEntity> _objectSet = null;
    
        public BaseRepository(IObjectContext objectContext)
        {
            if (objectContext == null)
                throw new ArgumentNullException("objectContext");
    
            _objectContext = objectContext;
            _objectSet = _objectContext.CreateObjectSet<TEntity>();
         }
    
         public IQueryable<TEntity> GetQuery()
         {
             return _objectSet;
         }
    
         public IEnumerable<TEntity> GetAll()
         {
            return _objectSet.ToList();
         }
    
         public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> where)
         {
            Contract.Ensures(Contract.Result<IEnumerable<TEntity>>() != null);
    
            return _objectSet.Where(where);
         }
    
    
         public TEntity Single(Expression<Func<TEntity, bool>> where)
         {
            return _objectSet.SingleOrDefault(where);
         }
    
         public void Delete(TEntity entity)
         {
             _objectSet.DeleteObject(entity);
         }
    
         public void Add(TEntity entity)
         {
             _objectSet.AddObject(entity);
          }
    }

    Every repository will inherits from this base class. As you can see the constructor will take an IObjectContext. I created an IObjectContext and let it add an ObjectContext to the WCF Operation’s OperationContext. So when the Repositories inside of an operation request an ObjectContext, it will get the one added to the OperationContext. By doing so, all Repositories used inside of an operation will use the same ObjectContext. Here is the implementation of the IObjectContext:

    public class WcfObjectContextAdapter : IObjectContext
    {
        public IObjectSet<T> CreateObjectSet<T>() where T : class
        {
            return Context.CreateObjectSet<T>();
         }
    
         public void SaveChanges()
         {
             Context.SaveChanges();
         }
    
         public void Dispose()
         {
             Context.Dispose();
          }
    
          public WcfObjectContextAdapter(IObjectContextFactory objectContextFactory)
          {
             if (objectContextFactory == null)
                 throw new ArgumentNullException("sessionFactory");
    
             if (Context == null)
                 Context = objectContextFactory.Create();
         }
    
         public ObjectContext Context
         {
             get
             {
                if (WcfOperationContainerExtension.Current == null)
                    return null;
    
                 return WcfOperationContainerExtension.Current.Context;
             }
             set
             {
                 if (CurrentOperationContext == null)
                     return;
    
                 CurrentOperationContext.Extensions.Add(new WcfOperationContainerExtension(value));
                 CurrentOperationContext.OperationCompleted += CurrentOperationContext_OperationCompleted;
             }
         }
    
         private void CurrentOperationContext_OperationCompleted(object sender, EventArgs e)
         {
             var context = WcfOperationContainerExtension.Current.Context;
             context.Dispose();
         }
    
         private OperationContext CurrentOperationContext
         {
            get { return OperationContext.Current; }
         }
    
         private class WcfOperationContainerExtension : IExtension<OperationContext>
         {
             public ObjectContext Context { get; set; }
    
             public WcfOperationContainerExtension(ObjectContext context)
             {
                Context = context;
             }
    
             public void Attach(OperationContext owner) { }
             public void Detach(OperationContext owner) { }
    
             public static WcfOperationContainerExtension Current
             {
                 get
                 {
                    if (OperationContext.Current == null)
                        return null;
    
                    return OperationContext.Current.Extensions.Find<WcfOperationContainerExtension>();
                 }
            }
        }
    }

    The WcfOperationContextAdapter will use an WCF IExtension<T> to keep the ObjectContext in the OperationContext, and also Dispose the ObjectContext when the OperationCompleted event is raised. TheWcfOperationContextAdapter takes as an argument of type IObjetContextFactory, it’s the factory which will configure and create an ObjectContext. In Part 2 I wrote about a ObjectContext factory, I made some changes to it and here is the code for new one:

    public class DefaultObjectContextFactory : IObjectContextFactory
    {
         [ImportMany(typeof(StructuralTypeConfiguration), AllowRecomposition = true)]
         private List<StructuralTypeConfiguration> _configurations = null;
    
         public ObjectContext Create()
         {
            return this.Create(ConfigurationManager.ConnectionStrings["AspenConnectionString"].ConnectionString);
         }
            
         public ObjectContext Create(string connectionString)
         {
             if (string.IsNullOrEmpty(connectionString))
                 throw new ArgumentNullException("connectionString");
    
             return this.Create(new SqlConnection(connectionString));
         }
    
         public ObjectContext Create(DbConnection con)
         {
             if (con == null)
                 throw new ArgumentNullException("con");
    
             if (_configurations == null)
                 this.Compose();
    
             var builder = CreateContextBuilder();
    
             return builder.Create(con);
         }
    
         private ContextBuilder<ObjectContext> CreateContextBuilder()
         {
             var builder = new ContextBuilder<ObjectContext>();
    
             if (_configurations != null)
                 _configurations.ForEach(c => builder.Configurations.Add(c));
    
             return builder;
         }
    
         private void Compose()
         {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    
            using (var catalogParts = new AggregateCatalog())
            {
                foreach (var assembly in assemblies)
                {
                    if (assembly.FullName.Contains("EntityMapping"))
                        catalogParts.Catalogs.Add(
                               new AssemblyCatalog(assembly));
                }
    
                using (var container = new CompositionContainer(catalogParts))
                {
                    container.ComposeParts(this);
                 }
            }
        }
    }

    How will all this thing works together you may ask? Well here is the process:

    When a call to a DomainService is made, the custom DomainService Factory (The code for the custom DomainService factory can be found in Part 4) will use Unity to resolve the DomainService. Unity will create the WcfOperationContextAdapter and pass an instance of the DefaultObjectContextFactory to the WcfOperationContextAdapter’s constructor. The WcfOperationContextAdapter will then be injected to the MemberRepostiory’s constructor. The MemberRepository will be passed into the DomainService. Here is the Unity container configuration:

    Container.RegisterType<MemberDomainService>();
    Container.RegisterType<IMemberRepository, MemberRepository>();
    Container.RegisterType<IGatheringRepository, GatheringRepository>();
    Container.RegisterType<IObjectContext, WcfObjectContextAdapter>(
                         new InjectionConstructor(new DefaultObjectContextFactory()));


    Here is the an example of a DomainService:

    [EnableClientAccess()]
    public class MemberDomainService : DomainService
    {
        readonly IMemberRepository _memberRepository = null;
        readonly IGatheringRepository _gatheringRepository = null;
    
         public MemberDomainService(IMemberRepository membershipRepository, IGatheringRepository gatheringRepository)
         {
             if (membershipRepository == null)
                 throw new ArgumentNullException("membershipRepository");
    
             _memberRepository = membershipRepository;
             _gatheringRepository = gatheringRepository;
    
         }
    
         [Invoke]
         public void Save()
         {
             using (var trans = new TransactionScope())
             {
                 _memberRepository.Add(new Member() { FirstName = "Ove", LastName = "Bengt" });
                 _gatheringRepository.Add(new Member() { FirstName = "OveG", LastName = "BengtG" });
                 trans.Complete();
             }
         }
    
         public IEnumerable<MemberDto> GetMembers()
         {
             var test = _gatheringRepository.GetAll();
             var members = _memberRepository.GetAll();
    
             return members.Select(m => Mapper.Map<Member, MemberDto>(m));
         }
    }


    Note: This DomainService will not be used in the Aspen project, it only do some stupid irrelevant stuffs, I only use it for testing purpose.


    What will I use in the Aspen Project


    I will keep the ObjectContext in an OperationContext, but will instead handle the Dispose and SaveChanges in a custom DomainService. Here is the temporary code I use and still on a testing stage:

    public class ObjectContextDomainService : DomainService
    {
        private IObjectContext _objectContext;
            
         public void Initialize(
                               IObjectContext objectContext,
                               DomainServiceContext domainServiceContext)
         {
             _objectContext = objectContext;
             base.Initialize(domainServiceContext);
          }
    
          protected override bool PersistChangeSet(ChangeSet changeSet)
          {
             _objectContext.SaveChanges();
              return base.PersistChangeSet(changeSet);
          }
    
          public override object Invoke(
                                 DomainOperationEntry operation,
                                 object[] parameters,
                                 out IEnumerable<ValidationResult> validationErrors)
         {
              var result = base.Invoke(operation, parameters, out validationErrors);
    
              _objectContext.SaveChanges();
    
              return result;
          }
    
          protected override void Dispose(bool disposing)
          {
              _objectContext.Dispose();
              base.Dispose(disposing);
          }
    }

    Here is how the earlier MemberDomainService will now look like:

    [EnableClientAccess()]
    public class MemberDomainService : ObjectContextDomainService
    {
        readonly IMemberRepository _memberRepository = null;
        readonly IGatheringRepository _gatheringRepository = null;
    
        public MemberDomainService(IMemberRepository membershipRepository,
    IGatheringRepository gatheringRepository) { if (membershipRepository == null) throw new ArgumentNullException("membershipRepository"); _memberRepository = membershipRepository; _gatheringRepository = gatheringRepository; } [Invoke] public void Save() { _memberRepository.Add(new Member() { FirstName = "Ove34", LastName = "Bengt" }); _gatheringRepository.Add(new Member() { FirstName = "Ove34G", LastName = "BengtG" }); } public IEnumerable<MemberDto> GetMembers() { var test = _gatheringRepository.GetAll(); var members = _memberRepository.GetAll(); return members.Select(m => Mapper.Map<Member, MemberDto>(m)); } }

    When the Save Invoke operation will be called the Member- and GatheringRepository will still use the same ObjectContext and when the Operation is done the SaveChanges of the ObjectContext will be called and also the Dispose method. For Add, Insert and Delete operations the ObjectContext will be called when the DomainService PersistChangeSet method is called and also do the Dispose of the ObjectContext. By using this solution, we can now share the UoW among Repositories and we don’t need to make a call to the SubmitChanges and we don’t need to Dispose it. The SubmitChanges of the Entity Framework ObjectContext will also use an implicit transaction, so we don’t need to use the TransactionScope class. This solution will now remove some cross-cutting concerns.

    The code for the Aspen project is on CodePlex, but the project is not yet published, we will in a near future publish the project.


    If you want to know when I will publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

    Read more...

  • Aspen – A sample app using Silverlight 4 and .Net 4.0 – part 3 of X – Repository implementation

    Note: The example code in this blog post is based on the VS2010 Beta 2, changes can be made until VS2010 hits RTM.

    In my previous post I wrote about how I use MEF and Entity Framework 4.0 Code-only feature. I have done a lot of refactoring and added the first Repository to the “Aspen” application since then. In this post I’m going to show you the refactoring I have made and how I have implemented the Repository for the Member Entity, MemberRepository.

    Changes made since the previous post


    I made some changes to the AspenObjectContextFactory. I made it more generic and renamed the class to ObjectContextFactory, the class now implements an interface, IObjectContextFactory:


    public
    interface IObjectContextFactory { ObjectContext Create(DbConnection con); ObjectContext Create(string connectionString); }


    The following code is the ObjectContextFactory:


    public
    class ObjectContextFactory : IObjectContextFactory { [ImportMany(typeof(StructuralTypeConfiguration), AllowRecomposition = true)] private List<StructuralTypeConfiguration> _configurations = null; public ObjectContext Create(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString"); return this.Create(new SqlConnection(connectionString)); } public ObjectContext Create(DbConnection con) { if (con == null) throw new ArgumentNullException("con"); if (_configurations == null) this.Compose(); var builder = new ContextBuilder<ObjectContext>(); if (_configurations != null) _configurations.ForEach(c => builder.Configurations.Add(c)); return builder.Create(con); } private void Compose() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var catalogParts = new AggregateCatalog(); foreach (var assembly in assemblies) { if (assembly.FullName.Contains("EntityMapping")) catalogParts.Catalogs.Add( new AssemblyCatalog(assembly)); } var container = new CompositionContainer(catalogParts); container.ComposeParts(this); } }


    The changes made to the “Aspen”ObjectContextFactory are a new constructor, taking a connection string as an argument and will create a SqlConnection by default. The other changes made to the class is to make sure it will only return an ObjectContext, not the AspenObjectContext as before (AspenObjectContext is now removed from the project).


    Repository


    When the ObjectContextFactory was in place I wanted to use it, so I created the first Repository, MemberRepository. The MemberRepository will take an IObjectContext as an argument. The reason why I want the Repository to take an IObjectContext is to make sure several repositories in the future can share the same ObjectContext and also remove some dependencies etc (Using the Dependency Inversion Principle). Entity Framework doesn’t have an IObjectContext interface and I will not use the ObjectContext because it will only make my Repository to be dependent on a detail instead of an abstraction (Will make it harder for me to write unit test). So I had to create my own IObjectContext interface:


    public interface IObjectContext : IDisposable
    {
       IObjectSet<T> CreateObjectSet<T>() where T : class;
            
       void SaveChanges();
    
    }


    The IObjectContext interface has two methods, the CreateObjectSet<T> and the SaveChanges. At the moment I don’t need more methods. I created an ObjectContextAdapter which inherits the IObjectContext interface, the ObjectContextAdapter will use the ObjectContextFactory to create an instance of an ObjectContext. Here is the ObjectContextAdapter:

    public class ObjectContextAdapter : IObjectContext
    {
        private ObjectContext _context = null;
        private IObjectContextFactory _objectContextFactory = new ObjectContextFactory();
    
        public ObjectContextAdapter(string connectionString)
        {
            _context = _objectContextFactory.Create(connectionString);
        }
    
        public ObjectContextAdapter(DbConnection con)
        {
           _context = _objectContextFactory.Create(con);
        }
    
        public ObjectContextAdapter(ObjectContext context)
        {
            _context = context;
        }
    
        public IObjectSet<T> CreateObjectSet<T>() where T : class
        {
            return _context.CreateObjectSet<T>();
        }
    
        public void SaveChanges()
        {
            _context.SaveChanges();
        }
    
        public void Dispose()
        {
            _context.Dispose();
        }
    }


    First I was thinking about making it possible to replace the IObjectContextFactory, but didn’t really find any reason to do so. I will see if I will made it possible in the future. The following is an example how the ObjectContextAdapter will be used in the production code:


    var objectContext = new ObjectContextAdapter(
          ConfigurationManager.ConnectionStrings["AspenConnectionString"].ConnectionString);
    
    var memberRepository = new MemberRepository(objectContext);



    Because the ObjectContextAdapter will create the instance of an ObjectContext, I can now for example use Unity or StructureMap etc to create an instance of an Repository and use dependency injection. Here is the how I have implemented the MemberRepository:



    public class MemberRepository : IMemberRepository
    {
        readonly IObjectContext _objectContext = null;
        readonly IObjectSet<Member> _objectSet = null;
    
        public MemberRepository(IObjectContext objectContext)
        {
            if (objectContext == null)
               throw new ArgumentNullException("objectContext");
    
            _objectContext = objectContext;
            _objectSet = _objectContext.CreateObjectSet<Member>();
        }
    
        public IQueryable<Member> GetQuery()
        {
            return _objectSet;
        }
    
        public IEnumerable<Member> GetAll()
        {
            return _objectSet.ToList();
        }
    
        public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> where)
        {
           return _objectSet.Where(where);
        }
    
    
        public TEntity Single(Expression<Func<TEntity, bool>> where)
        {
           return _objectSet.SingleOrDefault(where);
        }
    
    public void Delete(Member entity) { _objectSet.DeleteObject(entity); this.SaveChanges(); } public void Add(Member entity) { _objectSet.AddObject(entity); this.SaveChanges(); } private void SaveChanges() { _objectContext.SaveChanges(); } }


    Note: I could have done a more generic Repository without creating one for each Entity, but I decided to not do that. I prefer to have a Repository for each Entity instead of an generic one.


    The IMemberRepository interface implemented by the MemberRepository is kind of empty right now, it implements an generic IRepository<T> interface:

    public interface IMemberRepository : IRepository<Member>
    {
    }


    The following is the IRepository<T> code:


    public interface IRepository<T> where T : class
    {
       IQueryable<T> GetQuery();
           
       IEnumerable<T> GetAll();
            
       IEnumerable<T> Find(Expression<Func<TEntity, bool>> where);
            
       T Single(Expression<Func<TEntity, bool>> where);
            
       void Delete(T entity);
            
       void Add(T entity);
    }


    If you have any comments about anything, please let me know.

    Testing

    I will end this blog post about mentioning something about testing. Because I have created the IObjectContext interface, I don’t need to create a Stub for my MemberRepository in my unit tests, instead I can mock the IObjectContext. Here are the classes I use in my unit tests for the moment:

    The ObjectContext which will be passed to the MemberRepository:

    class MockObjectContext : IObjectContext
    {
       public IObjectSet<T> CreateObjectSet<T>() where T : class
       {
            return new MockObjectSet<T>();
       }
    
       public void SaveChanges()
       {
       }
    
       public void Dispose()
       {
       }
    }


    The ObjectSet for testing, MockObjectSet<T>:

    class MockObjectSet<T> : IObjectSet<T> where T : class
    {
       private List<T> _items = new List<T>();
    
        public void AddObject(T entity)
        {
            _items.Add(entity);
        }
    
        public void Attach(T entity)
        {
        }
    
        public void DeleteObject(T entity)
        {
          _items.Remove(entity);
        }
    
        public void Detach(T entity)
        {
        }
    public IEnumerator<T> GetEnumerator() { return _items.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public Type ElementType { get { return typeof(T); } } public System.Linq.Expressions.Expression Expression { get { return null; } } public IQueryProvider Provider { get { return null; } } }


    Here is how I can test my MemberRepository:

    var mockObjectContext = new MockObjectContext();
                
    var memberRepository = new MemberRepository(mockObjectContext);
    
    memberRepository.Add(new Member() { FirstName = "John", LastName = "Doe" });
    
    Assert.AreEqual<int>(1, memberRepository.GetAll().Count());

    This test is kind of dumb, but I decided to use some sort of TDD (Test Driven Design) first to make sure I find a good design for the Repository etc.

    If you want to know when I publish a new blog post to my blog, you can follow me on twitter: http://www.twitter.com/fredrikn

    Read more...

  • Aspen – A sample app using Silverlight 4 and .Net 4.0 – part 2 of X – MEF and EF 4 code-only

    Note: The code examples in this blog post will be based on technical previews and betas of .Net 4.0 and VS2010. So changes can be made before it hits RTM.

    If you haven’t read the first part about the Aspen project, you can find it here.

    In this part I will focus on the Entity Framework 4 CTP2 Code-only feature and the use of POCOs. To import some mapping configuration I have used MEF. I’m only working on the skeleton on the backend at the moment. What I have done so far is adding the first Entity, the Member! We want to use a POCO for the Entity and here is the code for the Member entity. No references to the EF assemblies, no annotations, no inherits or implementation of interfaces, just a plain old CLR object (POCO):

    public class Member
    {
        public int ID { get; internal set; }
    
        public string FirstName { get; set; }
    
        public string LastName { get; set; }
    }

    This Entity is far from completed we will add more properties later, but now I wanted to test the new code-only support, so I just added a few properties. The Entity exists in its own Class Library where we will add our Domain Model. I haven’t implemented a Repository for this Entity yet. I will be done when I’m satisfied with the code-only part and helper classes.

    When using POCO we need to create our own ObjectContext. I have created a simple one called AspenObjectContext. This class will later support more entities, but at the moment it will only have one, the Member. Here is the code for the AspenObjectContext:

    public class AspenObjectContext : ObjectContext
    {
        public AspenObjectContext(EntityConnection conn) : base(conn) { }
    
    
        public ObjectSet<Member> Members
        {
            get
            {
                return base.CreateObjectSet<Member>();
             }
        }
    }


    To create an ObjectContext we need to inherit the ObjectContext class from the System.Data.Objects namespace (System.Data.Entity.dll). The constructor will take an EntityConnection and also have a getter for accessing the ObjectSet of the Member entity. The AspenObjectContext is located in its own Class Library, at the moment together with the Repositories for the entities (which is not created yet ;)). I will see if I will keep the AspenObjectContext in the same assembly as the Repositories. The reason why I have placed it with the Repositories now is because they are going to use the AspenObjectContext. I will see if I will try to follow the Dependency Inversion Principle here, so the Repositories will not be dependent on the AspenObjectContext, instead of an abstraction (interface). In this case the app will only use Entity Framework 4 and that will not be changed. You can of course send me comments about what you would prefer etc.

    When using POCO we can use a EDMX for the mapping, but I decided to use the new code-only feature. When using the code-only feature we can for example create an EntityConfiguration class for the Entity, where a fluent-API can be used to configure the mapping between the database and the entity. Here is the mapping class for the Member entity:

    [Export(typeof(StructuralTypeConfiguration))]
    class MemberMappingConfiguration : EntityConfiguration<Member>
    {
        public MemberMappingConfiguration()
        {
             base.Property(m => m.ID).IsIdentity();
             base.MapSingleType(
                     m =>
                     new
                     {
                         ID = m.ID,
                         FirstName = m.FirstName,
                         LastName = m.LastName
                     }
                     ).ToTable("dbo.Members");
         }
    }

    By using the Property method of the EntityConfiguration class we can for example specify if a specific property should be the identifier. In this case the ID property of the Member entity. The MapSingleType is used to map the database columns (first property in the anonymous type) to the Member’s properties. The ToTable will tell which table the Member entity should map against, in this case the Members table.

    image


    Note: I often create the Domain Model first and test it before I focus on the database. But in this case I needed to test the code-only feature, so I created the database and added a table with the name Members. I’m thinking of renaming the table to Member instead. What is your comments on the naming of tables?

    The EntityConfiguration must be registered somehow so the AspenObjectContext can use the code-only mapping. This is done by using the ContextBuilder class and it’s Configurations property. In the future there will be several of EntiyConfiguration classes for each Entity, so I decided to use MEF to import the configurations. That is the reason why the [Export(typeof(StructuralTypeConfiguration))] is added to the MemberMappingConfiguration class. The configuration classes are added to their own class library. I want to use MEF to separate the configuration from the AspenObjectContext assembly. This is the part I would really like to have some comments on, how should you have done it etc. I decided to create a AspenObjectContextFactory class to create the AspenObjectContext instance and also use the ContextBuilder to configure the ObjectContext and the mappings. Here is the code of the AspenObjectContextFactory and where MEF is used to import the EntityConfiguration classes:

    public class AspenObjectContextFactory
    {
        [ImportMany(typeof(StructuralTypeConfiguration), AllowRecomposition=true)]
        private List<StructuralTypeConfiguration> _configurations = null;
    
         public AspenObjectContext Create(DbConnection con)
         {
             if (_configurations == null)
                 this.Compose();
    
             var builder = new ContextBuilder<AspenObjectContext>();
    
             if (_configurations != null)
                 _configurations.ForEach(c => builder.Configurations.Add(c));
    
             return builder.Create(con);
          }
    
    

    private
    void Compose() { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var catalogParts = new AggregateCatalog(); foreach (var assembly in assemblies) { if (assembly.FullName.Contains("EntityMapping")) catalogParts.Catalogs.Add( new AssemblyCatalog(assembly)); } var container = new CompositionContainer(catalogParts); container.ComposeParts(this); } } }

    The ContextBuilder’s Create method will create the AspenObjectContext, and the method needs a connection so the DbConnection base class is used as the type of the Create method’s argument. I’m planning to use Untiy as the IoC Container to inject dependencies (or maybe stay with MEF only), but aren’t there yet. The _configurations List has the MEF’s ImportMany attribute to imports the EntityConfiguration classes. The reason I use the StructuralTypeConfiguration as the contract for the Import and Export, is because I don’t want to use a string, and the EntityConfiguration is a generic class. The EntityConfiguration inherits from the StructuralTypeConfiguration class and the ContextBuilder’s Configurations’s Add method takes a StructuralTypeConfiguration (The Add method is used to add the configuraitons to the ContextBuilder).

    The Compose method will only be called when the _configuration is null for doing the composition. The Compose method will get all assemblies loaded to the AppDomain and will only add the Assemblies with the name “EntityMapping“. In this case I wanted to avoid configuration so I decided to use convention. I could just Load the assembly with the EntityConfigurations, but I decided to locate it without any specific configurations (In this case a referenced is needed. But I could have used configuration. Instead just specify the path to the mapping configuration assembly in a config file. By doing so I could easily replace the assembly and no reference is needed). I can now add other assemblies with the name EntityMapping, which can have some new mappings against new entities  etc. I would really like to have some comments on this solution also´, and have in mind this is still under development and changes can be made to the code. I only put something together for trying the code-only feature.

    Here is the code for using the AspenObjectContext (The code will only insert new Members):

    var aspenContext = new AspenObjectContextFactory().Create(
                 ConfigurationManager.ConnectionStrings["AspenConnectionString"].ConnectionString))
    
    aspenContext.Members.AddObject(new Member() { FirstName = "John", LastName = "Doe" });
    aspenContext.SaveChanges();
    
    aspenContext.Dispose();


    If you have any comments on this first part and also want to see some specific feature, please let me know. I would be glad if you can come with some suggestions.

    If you want to know when I publish more posts about this app and the progress, you can follow me on twitter: http://www.twitter.com/fredrikn

    Read more...

  • Aspen – A sample app using Silverlight 4 and .Net 4.0 – part 1 of X

    Together with Dag König and Danwei Tran at Microsoft, I’m building an app with the code name “Aspen”. This application will use most of the new features shipped with Visual Studio 2010, such as, Silverlight 4, Entity Framework 4, MEF, WCF RIA Services etc. We are going to use the MVVM pattern and a sort of Domain Driven Design (DDD) approach. Danwei is the GUI designer, she will use Sketchflow and Expression Blend 4. Dag König is the “Standards authority” and  will also do some development. My part is to be a developer, both backend and client-side. I will blog about our progress on my blog and that is the reason for the X in the title of this blog post. I don’t know how many parts it will be ;)

    Read more...

  • Silverlight – About validation when binding to custom forms – Part 2 using Silverlight 4

    In my first part about validation and binding to custom forms I wrote about how we could with some small hack enable the Validation Tooltip for a bounded control manually when we press a button. In this post I will instead use Silverlight 4 with Commanding and the INotifyDataErrorInfo interface to “manually” show the validation tooltip for a specific control.

    Read more...

  • Silverlight – About validation when binding to custom forms

    I have notice that some people have problems about how to implement User Input validation when they don’t use controls like the DataForm or DataGrid  etc, and instead bind directly to a TextBox or other user input controls. In this post I will write about different ways to handle validations. In this post I will work with a simple View. I will later add a post where I will use some new Validation features in Siverlight 4 and where I also use the MVVM pattern and Commanding.

    Read more...

  • Silverlight - Navigate to a specific Page using a Hyperlink

    Sometimes I think it’s hard to know what I should write about, my ideas comes from different sources. Some of my posts is based on questions people are asking on forums. If someone ask one specific question, it’s a big chance that someone else have the same kind of question, so I often blog about the solution so others kind find them. So this blog post will be about how we can from a HTML page navigate to a page hosting a Silverlight application and navigate to a specific .XAML page. Probably someone else have blogged about this before but I also use my blog as a reference for my self :P

    If we have our Silverlight control hosted on a page, for example default.aspx, the Silverlight will always show the same .XAML page when the page is loaded. This is because the visual root is set within the App file when the Application is started:

    private void Application_Startup(object sender, StartupEventArgs e)
    {
         this.RootVisual = new MainPage();
    }

    We must specify a RootVisual when the application is started and that will make the Silverlight application always show a specific page when we request the the page hosting the Silverlight application. So how can we from a hyperlink navigate to our Silverlight host page and specify which page we want to show? The RootVisual is of type UIElement, so we can set any kind of UIElement to be the RootVisual, for example a Grid and add a UserControl as a Child to the Grid, like this:

    private void Application_Startup(object sender, StartupEventArgs e)
    {
         var rootGrid = new Grid();
         this.RootVisual = rootGrid;
    
         rootGrid.Children.Add(new MainPage());
    }


    The following code will still show the MainPage UserControl but this time inside of a Grid. Because we can specify any kind of UIElement as the RootVisual, and in this example a Grid, we can now dynamically add UIElements to the RootVisual’s UIElement. By using Reflection we can create an instance of the UserControl from a string, so we can for example get the name of the UserControl we want to display form a QueryString. We can use an URL like this “default.aspx?page=Page2” when we want to request the page hosting the Silverlight application and show the Page2.xaml at startup.

    Here is the code which will get the Page from a QueryString:

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        var rootGrid = new Grid();
                
        this.RootVisual = rootGrid;
                
        var pageToShow = GetPageFromQueryString();
    
        if (string.IsNullOrEmpty(pageToShow))
            pageToShow = "MainPage";
    
        var userControlToShow = LoadPage(pageToShow);
    
        rootGrid.Children.Clear();
        rootGrid.Children.Add(userControlToShow);
    }
    
    
    private static UserControl LoadPage(string pageToShow)
    {
       var appType = App.Current.GetType();
    
       var userControlTypeString = appType.Namespace + "." + pageToShow;
    
       var userControlToShowType = Type.GetType(userControlTypeString);
    
       if (userControlToShowType == null)
          throw new Exception(string.Format("Can't find the Page with the type {0}", userControlTypeString));
    
       var userControlToShow = Activator.CreateInstance(userControlToShowType) as UserControl;
    
       if (userControlToShow == null)
          throw new Exception(string.Format("Can't create an instance of Page with the type {0}", userControlTypeString));
    
       return userControlToShow;
    }
    
    
    private static string GetPageFromQueryString()
    {
        string pageToShow = null;
    
        if (HtmlPage.Document.QueryString.Count > 0 && HtmlPage.Document.QueryString.ContainsKey("page"))
             pageToShow = HtmlPage.Document.QueryString["page"];
                
        return pageToShow;
    }

    Note: This code will not do any security check etc, it's only used to give you the basic ideas and the concept. So type-injection and what kind of pages a user are allowed to see etc is not taken care of in this example, I wanted it to only show the basic concept and not make the code too complex.

    To do something similar as the above code we can instead use the Frame control on our MainPage. The Frame control can show a specific control based on a URL like this “defaul.aspx#/Page2.xaml” (This URL will show the Page2.xaml content inside of the Frame control). To use the Frame Control you only need to add the Frame control to the XAML:

    <UserControl
        xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"  
       ....>
      <Grid x:Name="LayoutRoot">
    
          <navigation:Frame></navigation:Frame>
          
      </Grid>
    </UserControl>

    I hope this blog post have given you some ideas about how you you can navigate to your Silverlight application and specify which Page (UserControl) you want to show when the application is started.

    If you want to know when I publish a new blog post, you can follow me on twitter: http://www.twitter.com/fredrikn

    Read more...

  • My first day at my new work

    Today is my new day at my new work. I have now started to work for Iptor a .Net and Java consultant company in Gothenburg. My role will be coaching, mentoring, consulting and also as a instructor. My main role is to help companies with starting up new projects, helping them with architecture and design choice and make sure they use the correct tools for the correct task. The main focus will be everything from small web based and RIA apps to enterprise apps where I will spend a lot of time with Silverlight and of course other .Net frameworks. I will also work as an instructor to lift developers and architects to a reasonable level to succeed with the implementation of projects. Please don’t hesitate to contact me if you need any help with upcoming or existing projects.

    Read more...

  • Silverlight 4 - Make Commanding use lesser code

    In my previous post about using Silverlight 4 Commanding, I got a question why I didn’t use delegates etc instead of creating a lot of ICommand classes. In this post I’m going to show how you can reduce the number of ICommand classes.

    I have created a class with the name Command, this class implements the ICommand interface and uses two constructor arguments of a delegate type, in this case the Predicate<T> and Action<T>. I use the Predicate<T> for the ICommand.CanExecute because it takes one argument and returns a bool (I could have used the Func<T, TResult>), and I use the Action<T> for the ICommand.Execute, Action<T> doesn’t return anything and takes one argument.

    Here is the implementation of the Command class:

    public class Command : ICommand
    {
        public event EventHandler CanExecuteChanged;
    
        Predicate<Object> _canExecute = null;
        Action<Object> _executeAction = null;
    
        public Command(Predicate<Object> canExecute, Action<object> executeAction)
        {
            _canExecute = canExecute;
            _executeAction = executeAction;
        }
    
    
        public bool CanExecute(object parameter)
        {
            if (_canExecute != null)
                return _canExecute(parameter);
    
            return true;
        }
    
        public void UpdateCanExecuteState()
        {
           if (CanExecuteChanged != null)
                CanExecuteChanged(this, new EventArgs());
    }
        public void Execute(object parameter)
        {
            if (_executeAction != null)
                _executeAction(parameter);



    UpdateCanExecuteState(); } }


    Because the ICommand’s CanExecute and Execute method takes one argument of type ojbect (the value comes from the ButtonBase class’s CommandParamter) I decided to still use it, so the T in Preditcate<T> and Actiton<T> is of type object. In this example I also added the code to trigger the CanExecuteChanged event after the Execute is done. The reason I did that was because the CanExecute can be based on the result of the Execute. You can trigger the CanExecuteChanged event when you want the UI to check the CanExecute method. The CanExecute will normally take place when the UI is loaded, and before the Execute method is executed.

    To specify a Command in a ViewModel with the Command class I only need to return an instance of the Command where I pass two lambda expressions to the constructor. Here is an example:

    public class CommandingViewModel : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;
    
      private string _myTextBox;
      private Command _saveCommand = null;
    
      public string MyTextBox
      {
         get { return _myTextBox; }
         set
         {
             if (_myTextBox != value)
             {
                 _myTextBox = value;
    
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("MyTextBox"));
              }
          }
       }
    
    
       public ICommand SaveCommand
       {
          get
          {
    if(_saveCommand == null) _saveCommand = new Command ( p => string.IsNullOrEmpty(MyTextBox), p => MyTextBox = "Save Button Pressed" );




    return _saveCommand; } }
    }

    The first lambda expression passed to the first argument of the Command class will return true or false to enable or disable for example a Button where the Command is used. The second lambda expression is the code that will be executed when the Button is pressed (when the Command is executed). The “p” in the expressions will hold the CommandParameter result. Here is the View I used for the example above:

    <UserControl
        xmlns:view="clr-namespace:Commanding.ViewModel"
        ...>
    
        <UserControl.Resources>
            <view:CommandingViewModel x:Name="myView"/>
        </UserControl.Resources>
        
        <Grid x:Name="LayoutRoot" DataContext="{StaticResource myView}">
    
            <StackPanel VerticalAlignment="Center">
    
                <TextBox Height="50" Width="200" Text="{Binding MyTextBox}"/>
                <Button Content="Save" Height="50" Width="100" CommandParameter="1"  Command="{Binding SaveCommand}"/>
    
            </StackPanel>
           
            
        </Grid>
    </UserControl>


    As you can see, with a solution where we pass a lambda expression, we can reduce the number classes used and also make sure the Command code stays within the ViewModel.

    If you want to know when I publish new blog posts, then you can follow me on twitter: http://www.twitter.com/fredrikn

    Read more...