Contents tagged with Design

  • Use Extension method to write cleaner code

    This blog post will show you step by step to refactoring some code to be more readable (at least what I think). Patrik Löwnedahl gave me some of the ideas when we where talking about making code much cleaner.

    The following is an simple application that will have a list of movies (Normal and Transfer). The task of the application is to calculate the total sum of each movie and also display the price of each movie.

    class Program
    {    
        enum MovieType
        {
            Normal,
            Transfer
        }
    
        static void Main(string[] args)
        {
            var movies = GetMovies();
    
            int totalPriceOfNormalMovie = 0;
            int totalPriceOfTransferMovie = 0;
    
            foreach (var movie in movies)
            {
                if (movie == MovieType.Normal)
               {
                   totalPriceOfNormalMovie += 2;
                   Console.WriteLine("$2");
                }
                else if (movie == MovieType.Transfer)
                {
                    totalPriceOfTransferMovie += 3;
                    Console.WriteLine("$3");
                 }
             }
         }
    
         private static IEnumerable<MovieType> GetMovies()
         {
             return new List<MovieType>()
                                 {
                                     MovieType.Normal,
                                     MovieType.Transfer,
                                     MovieType.Normal
                                 };
         }
    }


    In the code above I’m using an enum, a good way to add types (isn’t it ;)). I also use one foreach loop to calculate the price, the loop has a condition statement to check what kind of movie is added to the list of movies. I want to reuse the foreach only to increase performance and let it do two things (isn’t that smart of me?! ;)).

    First of all I can admit, I’m not a big fan of enum. Enum often results in ugly condition statements and can be hard to maintain (if a new type is added we need to check all the code in our app to see if we use the enum somewhere else). I don’t often care about pre-optimizations when it comes to write code (of course I have performance in mind). I rather prefer to use two foreach to let them do one things instead of two. So based on what I don’t like and Martin Fowler’s Refactoring catalog, I’m going to refactoring this code to what I will call a more elegant and cleaner code.

    First of all I’m going to use Split Loop to make sure the foreach will do one thing not two, it will results in two foreach (Don’t care about performance here, if the results will results in bad performance, you can refactoring later, but computers are so fast to day, so iterating through a list is not often so time consuming.)

    Note: The foreach actually do four things, will come to is later.

    var movies = GetMovies();
    
    int totalPriceOfNormalMovie = 0;
    int totalPriceOfTransferMovie = 0;
    
    foreach (var movie in movies)
    {
        if (movie == MovieType.Normal)
        {
           totalPriceOfNormalMovie += 2;
           Console.WriteLine("$2");
        }
    }
    
    foreach (var movie in movies)
    {
        if (movie == MovieType.Transfer)
        {
            totalPriceOfTransferMovie += 3;
            Console.WriteLine("$3");
         }
    }


    To remove the condition statement we can use the Where extension method added to the IEnumerable<T> and is located in the System.Linq namespace:

    foreach (var movie in movies.Where( m => m == MovieType.Normal))
    {
        totalPriceOfNormalMovie += 2;
        Console.WriteLine("$2");
    }
    
    foreach (var movie in movies.Where( m => m == MovieType.Transfer))
    {
        totalPriceOfTransferMovie += 3;
        Console.WriteLine("$3");
    }


    The above code will still do two things, calculate the total price, and display the price of the movie. I will not take care of it at the moment, instead I will focus on the enum and try to remove them. One way to remove enum is by using the Replace Conditional with Polymorphism. So I will create two classes, one base class called Movie, and one called MovieTransfer. The Movie class will have a property called Price, the Movie will now hold the price:

    public class Movie
    {
        public virtual int Price
        {
            get { return 2; }
        }
    }
    
    
    public class MovieTransfer : Movie
    {
        public override int Price
        {
           get { return 3; }
        }
    }


    The following code has no enum and will use the new Movie classes instead:

    class Program
    {    
       static void Main(string[] args)
       {
           var movies = GetMovies();
    
           int totalPriceOfNormalMovie = 0;
           int totalPriceOfTransferMovie = 0;
    
           foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
           {
              totalPriceOfNormalMovie += movie.Price;
              Console.WriteLine(movie.Price);
           }
    
           foreach (var movie in movies.Where( m => m is MovieTransfer))
           {
             totalPriceOfTransferMovie += movie.Price;
             Console.WriteLine(movie.Price);
           }
         }
    
         private static IEnumerable<Movie> GetMovies()
         {
             return new List<Movie>()
                                {
                                     new Movie(),
                                     new MovieTransfer(),
                                     new Movie()
                                 };
         }
    }

    If you take a look at the foreach now, you can see it still actually do two things, calculate the price and display the price. We can do some more refactoring here by using the Sum extension method to calculate the total price of the movies:

    static void Main(string[] args)
    {
        var movies = GetMovies();
    
         int totalPriceOfNormalMovie = movies.Where(m => !(m is MovieTransfer))
                                             .Sum(m => m.Price);
    
         int totalPriceOfTransferMovie = movies.Where(m => m is MovieTransfer)
                                               .Sum(m => m.Price);
                
         foreach (var movie in movies.Where( m => !(m is MovieTransfer)))
               Console.WriteLine(movie.Price);
    
         foreach (var movie in movies.Where( m => m is MovieTransfer))
               Console.WriteLine(movie.Price);
    }


    Now when the Movie object will hold the price, there is no need to use two separate foreach to display the price of the movies in the list, so we can use only one instead:

    foreach (var movie in movies)
         Console.WriteLine(movie.Price);


    If we want to increase the Maintainability index we can use the Extract Method to move the Sum of the prices into two separate methods. The name of the method will explain what we are doing:

    static void Main(string[] args)
    {
        var movies = GetMovies();
    
        int totalPriceOfMovie = TotalPriceOfMovie(movies);
    
        int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);
                
        foreach (var movie in movies)
            Console.WriteLine(movie.Price);
    
    }
    
    private static int TotalPriceOfMovieTransfer(IEnumerable<Movie> movies)
    {
        return movies.Where(m => m is MovieTransfer)
                     .Sum(m => m.Price);
    }
    
    private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
    {
        return  movies.Where(m => !(m is MovieTransfer))
                      .Sum(m => m.Price);
    }


    Now to the last thing, I love the ForEach method of the List<T>, but the IEnumerable<T> doesn’t have it, so I created my own ForEach extension, here is the code of the ForEach extension method:

    public static class LoopExtensions
    {
       public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
       {
           Contract.Requires(values != null);
           Contract.Requires(action != null);
    
           foreach (var v in values)
               action(v);
       }
    }


    I will now replace the foreach by using this ForEach method:

    static void Main(string[] args)
    {
        var movies = GetMovies();
    
         int totalPriceOfMovie = TotalPriceOfMovie(movies);
    
         int totalPriceOfTransferMovie = TotalPriceOfMovieTransfer(movies);
    
         movies.ForEach(m => Console.WriteLine(m.Price));
    }


    The ForEach on the movies will now display the price of the movie, but maybe we want to display the name of the movie etc, so we can use Extract Method by moving the lamdba expression into a method instead, and let the method explains what we are displaying:


    movies.ForEach(DisplayMovieInfo); private static void DisplayMovieInfo(Movie movie) { Console.WriteLine(movie.Price); }


    Now the refactoring is done, or?

    EDIT: It's not done. Niclas Nilsson wrote a good comment that I actually do two things in the TotalPrice... methods, a filtering and a Sum. So both a command and a query. so it will not follow the Command and Query Principle. To make the code more seperated by concerns:

    The TotalPriceXXX method are removed and replaced with on called TotalPriceOfMovie. Two properties are added, one for returning the normal movies and one for returning the transfer movies. Here is the result of the new refactoring:

    static void Main(string[] args)
    {
        int totalPriceOfMovie = TotalPriceOfMovie(NormalMovies);
    
        int totalPriceOfTransferMovie = TotalPriceOfMovie(MovieTransfers);
                
        foreach (var movie in movies)
            Console.WriteLine(movie.Price);
    
    }
    
    private static int TotalPriceOfMovie(IEnumerable<Movie> movies)
    {
        return movies.Sum(m => m.Price);
    }
    
    private static IEnumerable<Movie> NormalMovies
    {
        get { return AllMovies.Where(m => !(m is MovieTransfer)); }
    }
    private static IEnumerable<Movie> MovieTransfers
    
    { get { return AllMovies.Where(m => m is MovieTransfer); }
    }

    private static IEnumerable<Movie> AllMovies
    { get { return GetAllMovies(); }
    }
    private static IEnumerable<Movie> GetMovies()
    {
         return new List<Movie>()
                    {
                      new Movie(),
                      new MovieTransfer(),
                      new Movie()
                    };
    }
    
    Note: The GetMovies() method in this code is just a fake method to return fake data, so it could instead be a call to a Repository etc.
    

    I think the new code is much cleaner than the first one, and I love the ForEach extension on the IEnumerable<T>, I can use it for different kind of things, for example:

    movies.Where(m => m is Movie)
          .ForEach(DoSomething);


    By using the Where and ForEach extension method, some if statements can be removed and will make the code much cleaner. But the beauty is in the eye of the beholder. What would you have done different, what do you think will make the first example in the blog post look much cleaner than my results, comments are welcome!

    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...

  • Distributing domain entities over the wire

    When we design our domain entities we don’t have a presentation layer or database in mind. The domain entities are core business objects located on the server or client side based of what kind of application we are building. Domain entities aren’t designed for distribution. When we realize that we need a distribution, we shouldn’t distribute the entities, instead collect the data we need to distribute and create a data transfer object (DTO) instead. Have the network in mind, a domain entity aren’t designed with a network in mind and of that reason not suitable for distribution. When we create our domain entities, they aren’t designed for presentation purpose, they are designed to fulfill business needs. You should be careful when you start thinking about returning a domain entity to the View when using a patterns like MVC, instead use DTO or a ViewModel, because once again the domain entities aren’t designed with presentation in mind, and aren’t often suitable for presentation purpose. It’s often better to map them to a DTO or ViewModel, objects that are suitable for presentation purpose or passed over the wire.

    Read more...

  • RIA Architecture with Silverlight in mind

    Rich Internet Application (RIA) is an interesting topic. More and more business apps are moving into to the cloud, and more and more will have better User Experience (Ux). According to Gartner Research, nearly 60 percent of all new application development will include RIA technology by 2010. Today we can use different technologies to build a RIA, for example, AJAX, Flash and Silverlight etc. When it comes to AJAX we will soon reach the top of what we can do with it, because of the limitation of HTML, Client-side scripts and the browsers etc. That makes Silverlight and Flash more interesting regarding to me. But what is RIA? RIA It’s an internet applications that looks and feels like desktop applications, it also provide most of the maintainability and deployment benefits of Web applications. A RIA client can have state, so to increase User Experience, the user can work with data for a while until it will be passed down to the server for processing. Because the client side of a RIA can have state and work with data for a while, it’s extra important to have concurrency in mind. Some other users can have changed the data during the time we have worked with our copy. When developing RIA Clients we need to have several things in mind, for example a RIA is often running within an execution container in the Browser, so people can hit the refresh button or use the back and forward buttons, which can be reload the whole app and the current state can be gone. When we creates a large RIA, we can’t let users wait for hours until the application is loaded and started, so we need to load views etc on demand, and split them into small “modules”. Developing a RIA is not like developing a stateless ASP.NET app.

    In this post I will write about the architecture and design I use when building a RIA with Silverlight.

    The following is a figure of an Architecture of a typical RIA implementation:


    RIA_arch

    The Presentation Layers purpose is to make sure users gets the best possible User Experience. The Presentation Layer of a RIA should not include too much business logic, instead it will communicate with a Web Server to perform business operations. This is done by accessing a Application Service Layer which in turn will communicate with the Domain Model [Evans DDD]. In this post I will focus more on the Application Service Layer and the Presentation layer, rather then the other layers or tiers.

    Business Logic, where to place it?

    Because a RIA often look and feel like a desktop application, and can have state, it can be appealing to add a lot of business logic to the Presentation Layer. But try to not do that. The only kind of business logic that should be in the Presentation Layer is user input validations, and business logic that can increase user experience and increases performance overall, for example by avoiding communications to the Web Server or some expensive business operations, which can for example improve the UI responsiveness. Start with your business logic implementation on  the server and expose them through services. It will make sure you don’t start adding a lot of business logic to the client at the first place. One problem with the business logic is that same business logic can exists on both the client and server side. For example validations. To address this issue you can for example use the Microsoft .NET RIA Services. If you don’t want to use the .NET RIA Services, make sure you group the business logic into a separate assembly, which you can share both with the Server and client, or at least make sure you reuse the same kind of code and language, so you can easily replace the code when changes is made to the business logic on the server and should also be changed on the client side. Some logic should never be on the client side, such as highly sensitive business logic. Add it to the server for security reasons. If the client side are going to need a lot of business logic that can be changed often, make sure to add it to a downloadable module. It will make it easy to replace the logic without re-downloading the entire RIA application.

    How to share Business logic between tier with .Net RIA Services

    The .NET RIA Services lets us create a DomainService where we can add our CRUD operations and custom queries. We can also use metadata to add shared validation logic and also add code that should be shared between the client and the server. .NET RIA Services will locate our DomainServices, metadata and shared code, and generate client-side classes for us. The following code is a simple DomainService which will return a list of an “Entity” (You can find more about design considerations etc when creating entities later in this post):

    [EnableClientAccess()]
    public class UserService : DomainService
    {
        private UserDataService _userDataService = new UserDataService();
    
        [Query(PreserveName=true)]
        public IEnumerable<User> Followers()
        {
            return this._userDataService.Users;
        }
    }


    Here is en implementation of the User Entity:


    public partial class User
    {
       [Key]
       public string ID { get; set; }
    
       public string Name { get; set; }
    
       public string Description { get; set; }
    }


    To add validations that are applied on both tiers we can create a metadata class:

    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
        internal sealed class UserMetaData
        {
            [Required]
            public string Name;
    
            [Required]
            [StringLength(255, MinimumLength = 0)]
            public string Description;
        }
    }


    The above metadata class will make sure that the generated Entity for the client-side will have the validations specified by using attributes. When it comes to validation, make sure to validate both on the client side to improve user experience, and server side validation for security. The magic to share business logic between the client and server is by using code generation. There is only one place the business logic is added, and it’s on the server side, but can be shared with the client side without adding duplications.


    Communication

    To increase the user experience and performance, the communication from the client side to the server must be made asynchronous. If not we can block the UI thread. If long running code is needed, it’s worth to consider if a background thread should be used or not. Here is an example how the Silverlight’s BackgroudWorker can be used to run a thread in the background:


    public MainPage()
    {
        InitializeComponent();
    
        var bw = new BackgroundWorker();
        bw.RunWorkerCompleted += bw_RunWorkerCompleted;
        bw.DoWork += bw_DoWork;
        bw.RunWorkerAsync();
    }
    
    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        //perform the work
        e.Result = result of the operation if any
    }
    
    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
           //handle exception
    
        //get the result from e.Result and do for example update UI
    }

    Note: When performing operations in a background thread, it can be advisable to show the user the progress of the operation (if the user should see any result after the operation is completed). The BackgroundWorker class has a ProgressChanged support.

    To communicate to the Server, WCF, APS.NET WebServices, .NET RIA Services, ADO.NET Data Service, WebClient etc can be used. When passing data from server to the client or back, try to remember that there can be some bandwidth limitations. When creating a distributed system, objects shouldn’t be distributed. So don’t distribute your domain model’s entity. Instead create new kind of “resources”. For example by using formats like JSON, XML or DataContracts, and only pass the data that is needed by the presentation layer. Try to focus on what data a specific View needs. If you need to save data on the client-side for offline support, make sure to use the Isolated Storage or the new SaveFileDialog added to Silverlight 3.0. Don’t use a local databases, instead make sure you make a call to a Service. If it would be catastrophic to lose state data on the client, make sure to store it on the server. Try to minimize the number of round-trips to the server. Make sure to filter all data at server rather than at the client to reduce the amount of data that must be sent over the network. By using .NET RIA Services, we can without adding new methods to the DomainService, make sure a Query is passed as an argument to the server and the server will do the filtering. Try to avoid creating too much queries on the client side, if you have common quires witch is located on several Views on the client side, make sure you add a common query as a method to a DomainService instead. It will make it much easier for you to maintain  the application.

    The following is an example of how WebClient together with XDocument can be used to retrieve data from the server, with a REST like way:

    public MainPage()
    {
         InitializeComponent();
    
         var wc = new WebClient();
    
         wc.OpenReadCompleted += wc_OpenReadCompleted;
         wc.OpenReadAsync(new Uri("/User/Followers", UriKind.Relative));
    }
    
    void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        XDocument xmlUsers = XDocument.Load(e.Result);
    
        var users = from user in xmlUsers.Descendants("user")
                    select new
                           {
                             ID = (string)user.Element("ID").Value,
                             Name = (string)user.Element("Name").Value,
                             Description = (string)user.Element("Description").Value
                           }; 
    
    }



    The “/User/Followers” URI used by the WebClient, can for example be a REST API created by using ASP.NET MVC:


    public class UserController : Controller
    {
        public ActionResult Followers()
        {
            var userDataService = new UserDataService();
    
            return View(userDataService.Users);
        }
    }
    
    Followers.aspx 
    
    <%@ Page Language="C#" 
             Inherits="System.Web.Mvc.ViewPage<List<Models.User>>" %> 
    <users type="array"> 
        <% foreach (var user in ViewData.Model) { %>
            <user> 
                <id><%= Html.Encode(user.ID)%></id> 
                <name><%= Html.Encode(user.Name)%></name> 
                <description><%= Html.Encode(user.Description)%></description> 
            </user>
        <% } %> 
        </user> 
    </users>


    The following is how we can use a WCF Service to retrieve data from the server. The WCF Service is part of the Application Service Layer:


    [DataContract]
    public class User
    {
        [DataMember]
        public string ID { get; set; }
    
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public string Description { get; set; }
    }

     

    public class UserService { private UserDataService _userDataService = new UserDataService(); [OperationContract] public IEnumerable<User> GetFollowers() { return _userDataService.Users; } }

     

    MainPage.xaml.cs

    public MainPage()
         {
             InitializeComponent();
    
             var us = new UserServiceClient();
             us.GetFollowersCompleted += us_GetFollowersCompleted;
             us.GetFollowersAsync();
             
             
             myGrid.ItemsSource = _uc.Users;
             _uc.Followers(_uc.Users.AsQueryable<User>().Where( c => c.ID == "1") , null);
    
         }
    
         void us_GetFollowersCompleted(object sender, GetFollowersCompletedEventArgs e)
         {
             myGird.ItemSource = e.Result;
         }


    As you can see in the above code, a DataContract is created, this contract should only return the information that the client needs. To minimize the data sent to the client over the network, it can be good to create data contracts for each View (Client side “forms”), but be pragmatic. If we will have more than one View that need the same data, we can reuse the same contracts if the different is only one or two properties, it may be unnecessarily to create two data contracts to reduce the data sent over the wire. But still have bandwidth in mind. I often create one Service per View, and if there are some other Views that should reuse the exact same kind of operations I reuse the Service, or create a new Service which in turn will access the other Service. It depends on the app and the Views etc.

    To make a call to a WCF Service, a Service Reference is needed to locate the Service and to create a client-side proxy class to make it easy to communicate with the Service.

    In the first example in this post I showed some .NET RIA Services code, where I created a DomainService. When the solution is build a generated proxy class will be created and added to the Silverlight project. This class is called a DomainContext. Here is an example where .NET RIA Services DomainContext is used to communicate to the DomainService:


    public partial class MainPage : UserControl
    {
        UserContext _uc = new UserContext();
    
        public MainPage()
        {
            InitializeComponent();
    
            var us = new UserServiceClient();
            us.GetFollowersCompleted += us_GetFollowersCompleted;
            us.GetFollowersAsync();
            
            myGrid.ItemsSource = _uc.Users;
            _uc.Followers();
    
        }
    
        void us_GetFollowersCompleted(object sender, GetFollowersCompletedEventArgs e)
        {
            myGird.ItemSource = e.Result;
        }
    }


    Now when you have seen some different ways to communicate with a Service form the Client, we can focus more on the data passed to the client from the server and back..

    Data

    When creating a distributed system we should never distribute an object. So don’t try to pass entities from the Domain Model to the client side. Instead create a new model only for presentation purpose. For example with DataContracts or if you are using REST a resource, or a thin object only used for presentation purpose if you are using .NET RIA Services. Here is a figure over how I often build my applications:

    ria_arch2

    Note: The View Model is not the Pattern ViewModel. It’s a model created for presentation purpose only, for example a DataContract, or at .NET RIA Services Entity etc.

    One of the important part when creating a RIA, is to focus on the “model” that the View should use. If we for example should list all Customers, and we only need display three properties, we creates a class/resource or DataContract for that purpose, for example:

    public partial class Customer
    {
       [Key]
       public string ID { get; set; }
    
       public string Name { get; set; }
    
       public string Country { get; set; }
    }


    If we need more detail about a Customer, we create a new class with the properties needed:


    public partial class CustomerDetail { [Key] public string ID { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public string Email { get; set; }

    ... }


    When building RIA, performance and bandwidth is something we should have in consideration, so it’s not sure a user will show detailed information about a Customer, so in this case we make sure we have two methods in our Application Service Layer, GetCustomer and GetCustomers. The GetCustomer will return the CustomerDetail class and the GetCustomers the Customer class. If we know that a user will show all the information of a customer, and will get a set of Customers to always work with. We can create a method that will return a list of CustomerDetails. If we create a small applications for few users and it’s an intranet application, the bandwidth may not be a problem, so in that case we can return more data that isn’t needed in specific scenario but is needed for other scenarios to reduce the number of classes created etc. So everything depends on!

    Presentation Layer Pattern

    I often use a UI patterns like the Presentation Model/ViewModel pattern. The MVC pattern could be used, but I prefer the Presentation Model pattern in a RIA. If you are interested in how a Presentation Model could look like when using Silveright, you can read the following post on my blog: http://weblogs.asp.net/fredriknormen/archive/2009/01/30/how-the-presentation-model-could-look-like-when-using-silverlight-2-0.aspx

    The end

    There is so much to write about when it comes to the topic of this blog post but I hope you have found some useful tip. If there is something you don’t agree on, please let me know, I only share my experience ;)

    Read more...

  • Isn't it boring to write crosscutting concerns?

    To make sure we have clean code and make it easy for us to maintain, we should try to be lazy and reuse code as much as possible, we should also avoid redundant code. But when it comes to crosscutting concerns, we have to be redundant, or? What code is mostly redundant in our code? I will assume that code to check security and logging exceptions are the most redundant code we write. A method should only do one thing, but we can't skip crosscutting concerns, we need it. So basically several method will do more than one thing. Wouldn't it be much better if we only focus on the core concern and skip the crosscutting concerns when we write our code? How can we skip the crosscutting concerns but still has it? The answer is Aspect Oriented Programming (AOP). The PAG team has a Policy Injection Application BLock (PIAB) which we can use to intercept our crosscutting concerns into our code, we also have Spring.Net and some other frameworks. By using AOP frameworks we don't need to write the same code for logging exception etc over and over again, we will also have a much cleaner code, and our focus will only be the core concern. Oh, I feel so lazy, but why should I spend time to write code that do the same thing over and over again, it's so boring, isn't it :P Are you tired of writing crosscutting concerns over and over again, and do you use AOP today?

    Read more...

  • Returning IQueryable<T>

    Since LINQ was added to the .Net Community as a new wonderful new player, more and more solutions I have seen returns the IQueryable<T> from the Data Access Layer. One reason is to easy create different kind of queries in an easy way and execute them. Some developers use the IQueryable<T> interface to create a light weight interface for the Data Access Layer. It's an interesting solution, but at the moment I don't like it.

    Read more...

  • Using Web Services in a 3-tier architecture

    During the age of the Windows DNA, most of us developers used COM/COM+ and a 3-tier architecture. Where we separate concerns by placing the views to present data into a layer called PL (Presentation Layer), we add all business logic into one single layer called BLL (Business Logic Layer), all code that handle data access was also placed into its own layer called DAL (Data Access Layer). During this time when Windows DNA was a hot topic, most application used this architecture.


    3tier


    By using DCOM it was easy to distribute the different components in the layers into distinct tiers. DCOM had its advantage and also disadvantage (DCOM hides the "distribution" and distribution could be done after application was written without the developers awareness, most applications wasn't designed for distribution purpose.). There was few application I was involved with that used DCOM, and I will in this article focus on the application that didn't use DCOM. The 3-tier architecture was well defined and common used. Several applications today used this architecture. When .Net arrived several developers was scratching their heads, it was a whole new platform for most of them and a difficult and confused time began, "how should this 3-tier architecture be applied on the .Net platform?". Web Services was introduced somewhere around this time and that was a bright light for some solution architects and developers, now they understand how to apply the 3-tier architecture on the .Net platform, the answer was to replace COM/COM+ components with Web Services. So instead of using a binary standard for the communication, XML and HTTP was used.

    3tier_WebService


    Even today several applications uses the 3-tier architecture with Web Services as a replacements for COM/COM+ and even a replacements for DCOM and that is understandable. But replacing COM/COM+ with Web Services for applications on a single machine, with no reuse or integrations with other applications in mind, is something that make me sad. Now when we have WCF (Windows Communication Foundation), developers start to replace Web Services with WCF. There are several applications running on a single machine with no attention of integration with other systems that uses different WCF Services for the Business Logic and the Data Access. I will not say that this is totally wrong decision made by architects, but it will affect performance and scalability, and can affect it badly. There is absolutely no reason to use WCF Services if the application is running locally or on a single machine where no integration with other systems are of interest. Even if there are integration in mind, there is no reason to have the Data Access Layer as a WCF Service, because most applications will reuse the business logic, so the layer top of the Business layer should be a WCF Service not the underlying layers. There are some exceptions, if we have moved the Data Access Layer into a distinct tier, and several applications should reuse or have access to the same data source; but can't or aren't allowed for a direct connection to the data source, the Data Access could be implemented as a WCF service. In that case all communication will go via the WCF Service.

    If there is no reason of using Web Services or WCF Services as a replacement for COM/COM+ in applications with not interest in integration, what is the solution? A simple Class Library! Best performance, easy to add, easy to implement. Since .Net arrived I toke the advantage of the platform and use Object Oriented Programming. Now during the past few years I have adopt Domain Driven Design. How about you, do you still use the 3-tier architecture and using Web Services of WCF, or something else?

    Read more...

  • Map Objects to one Object

    In my previous post I wrote about how we could use Dynamic Compilation for mapping object to object in a configuration file, mosly for fun to simply try something different. I spend a few minutes to see if I could do something more with it. It ended up that I can use it to several things, like creating Factories, or send in different kind of objects and map several into one. Here is how I for example can send in more domain object to map them into a PresentationCustomer:

    var presentationCustomer = map.Map<PresentationCustomer>(
                                        "CustomerToPresentationCustomer", 
                                        customer, 
                                        address);

    My configuration file look like this:

    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, Address address)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = customer.FirstName,
                           LastName = customer.LastName,
                           Street = address.Street
                      };
    }

    Some comments I got was also to automatically map properties from object with the same name, so I added an extension method called MapTo, to make that possible, it will also open up support for mapping specific properties manually:

    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, string lastName)
    {
          var presentationCustomer = new PresentationCustomer();
    
          customer.MapTo(presentationCustomer);
    
          presentationCustomer.FullName = customer.FirstName + " " + customer.LastName;
    
          return presentationCustomer;
    }


    I did also add support so other developers can simply add their own code which could be used by the configuration file. It's done by adding the namespace and an assembly of the code to the mapper.

    DynamicMapper map = new DynamicMapper();
    
    map.Assemblies.Add("MyHelper.dll");
    map.Namespaces.Add("MyHelper");
    
    var presentationCustomer = map.Map<PresentationCustomer>(
                                                   "CustomerToPresentationCustomer", 
                                                    customer, 
                                                    "Normén");


    Here is the MyHelper:


    namespace MyHelper
    {
        public static class MyExtension
        {
            public static string GetName(this string value)
            {
                return "Fredrik";
            }
        }
    }


    I can now use this extension method in my configuration file:


    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, string Name)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = name.GetName(),
                           LastName = customer.LastName,
                           Street = address.Street
                      };
    }


    Because I can pass in several objects and map them to one single object, I can also pass in XmlDocument, DataSet, DataTable and SqlDataReaders etc and map them to an object:


    var presentationCustomer = map.Map<PresentationCustomer>(
                                        "CustomerToPresentationCustomer", 
                                        customer, 
                                        sqlReader);
    public PresentationCustomer CustomerToPresentationCustomer(Customer customer, SqlDataReader reader)
    {
           return new PresentationCustomer()
                      {
                           ID = customer.ID,
                           CompanyName = customer.CompanyName,
                           FirstName = customer.FirstName,
                           LastName = customer.LastName,
                           Street = reader["Street"]
                      };
    }


    I can think of using this solution if I don't use an ORM but still want to bind data from a SqlDataReader to an object, or combine several object and use formatting and specifying default values which could be changed over time, and when it does I don't need to recompile my code, only change the configuration file.

    Read more...

  • What do you think about using a presentation model for presenting your domain model?

     

    I’m writing a small app for a demonstration purpose. What I have is a domain model where I have a Customer, I also have CustomerRepository.

    public class Customer
    {   public int ID { get; set; }
    
           public string CompanyName { get; set; }
    
           public string FirstName { get; set; }
    
           public string Lastname { get; set; }
    }
    public interface ICustomerRepository
    {
           IList<Customer> GetCustomers();
    
           Customer GetCustomerByID(int ID);
    
           void Remove(Customer customer);
    
           void Update(Customer customer);
    
           void Add(Customer customer);
    }

    I decided to not make the Customer immutable and use the new automatic property feature to speed up the creation of the Customer entity. My CustomerRepository have some few method. About the Get methods, should they have the name GetCustomerByID, or GetByID or only Get!? The name of the class indicates that it's a customer I want, do I need to repeat my self and add the word Customer to the method name? The argument of the GetCustomerByID method indicates that I need an ID, so the method could be Get(int ID). But of some reason I feel more comfortable to name it GetCustomerByID, because the method should get a Customer based on a given ID. What do you think, how should you have named that method and why, please feel free to add a comment. This was out of the topic of this blog post, but I'm very interested in how you should have named it.

    I use ASP.Net to build my client. What I was needed was a model for the presentation, I call it Presentation Model. A Presentation Model is a model used for presentation purpose only. For example if I want to bind a Customer entity to a Grid and one column should display the FullName of a Customer, it's not sure that every country want to display the FirstName first. I didn't want to add the logic of how a FullName should be displayed into the code-behind of my page or on the .aspx page. Instead I created a Presentation class for my Customer which has a FullName property.

    public class PresentationCustomer : MyApp.DomainLayer.Entities.Customer
    {
        public PresentationCustomer()
        {
        }
    
    
        public string Fullname
        {
            get { return base.FirstName + " " + base.Lastname; }
        }
    }

    I still wanted to have the same members as the Customer entity so I inherited the Customer class and added a Fullname property to my new Presenstion model. I didn't know what I should named the Presentation class of the Customer, so I used what it is, a presentation of the Customer (PresentationCustomer). In this example I do not have logic to display the FirstName and LastName in a specific order. I often use a Presentation Model in my app, for example say that I have a checkbox, this should be selected or note based on the domain entities state. Instead of adding a condition statement to my code-behind, I use a presentation class with a property which return true or false based on condition, for example let say I have a Customer and I wanted to mark a checkbox if the Customer is and adult or not. The only information my Customer entity has is Age. So instead of adding the code into the code-behind or .aspx page, I created a Presentation class of the Customer and added a IsAdult property, which I bound to a checkbox.

    public bool IsAdult
    {
        get { return (this.Age > 18) }
    }

    This will of course require me to write several of new classes, but by using a Presentation Model I can easy reuse my client even if my underlying data source is changed, just map the new data to my Presentaion Model, so the data could for example be simple XML documents. It's still the Presentation Model my Views will work against and not directly to my domain model. As you may know if we use a ObjectDataSource and bind an object to it, only the fields which are bounded to the Grid will be updated and passed down to the Update method. In that case we can't map our ObjectDataSource directly to a Repository. Well we can hook up to the Updating event and get the original customer and make sure the unbound field will be filled with the original value instead of getting the null value. But use a another solution to reduce the code in the code-behind, I use a "Controller", and each View can have it's own "Controller" which can handle View specific problems. So I can add a Update method to my "Controller" which will be used by a ObjectDataSource, this method can then help me solve the null problem with unbound fields.

    When I use a Presentation Model, I need a way to easy map my Customer to a PresentationCustomer, this can for example be done by using constructor injection, where I inject the Customer entity into the PresentationCustomer's constructor.

    public class PresentationCustomer
    {
        Customer _customer;
    
        public PresentationCustomer(Customer customer)
        {
            this._customer = customer;
        }
    
        public string Fullname
        {
            get { return this._customer.FirstName + " " + this._customer.Lastname; }
        }
    }

    In this case if I want to use the Customer entity's members, I need to add all of them again to the PresentationCustomer class. This is something that I didn't wanted to do. I wanted to reuse as much code as possible. So I decided to inherit the Customer class instead and do a manual mapping by using code. I could have used a object to object mapping tool, but that may require me to setup the mapping, and the time to do that is the same time to write the mapping by code.

    To make sure my Views work against my Presentation Model, I created a new class which should also have the responsibility to handle the flow and state of my Views. I'm so bad at naming things, but I used the name CustomerController. This class has several method to handle navigation after a new customer is added or updated etc. Two methods that I have is ViewCustomer and GetCustomers. The ViewCustomer method's responsibility is to display a Customer, the GetCustomers should be used by a ObjectDataSource control to fill a Grid with Customers, those method should return and use a PresentationCustomer and not the Customer entity. To do that I need to map all Customer into PresentationCustomer. I did that by using the new object initializer feature of C# 3.0.

    private PresentationCustomer MappCustomerToPresentationCustomer(Customer customer)
    {
         return new PresentationCustomer()
         {
            ID = customer.ID,
            FirstName = customer.FirstName,
            Lastname = customer.Lastname,
            CompanyName = customer.CompanyName
         };
    }

    The ViewCustomer and GetCustomers in the CustomerController now use this method, the implementation of the methods look like this:

    public void ViewCustomer(int? ID)
    {
        if (!ID.HasValue)
            throw new ApplicationException(Resources.Resource.CustomerIDCantBeNullArgumentValidation);
    
        var customer = this._customerRepository.GetCustomerByID(ID.Value);
    
        if (customer == null)
            throw new ApplicationException(string.Format(Resources.Resource.CantFintCustomerByIDErrorMsg, ID));
    
        var presentationCustomer = this.MappCustomerToPresentationCustomer(customer);
    
        base.AddPageState("Customer", presentationCustomer);
        base.MoveToView("CustomerDetails.aspx");
    }
    
    public IList<PresentationCustomer> GetCustomers()
    {
        var customers = this._customerRepository.GetCustomers() as List<Customer>;
    
        var presentationCustomers = new List<PresentationCustomer>();
    
        customers.ForEach(c => presentationCustomers.Add(this.MappCustomerToPresentationCustomer(c)));
    
        return presentationCustomers;
    }

    My question is how should you have done it? Is there a way you think is much easier and faster way to implement it, do you like this approached with a Presentation Model or is there anything that you think is much better? Please feel free to add a comment, I would like to hear about your thoughts and suggestions etc.

    Read more...