Contents tagged with VS2010

  • Design by Contract with Microsoft .Net Code Contract

    I have done some talks on different events and summits about Defensive Programming and Design by Contract, last time was at Cornerstone’s Developer Summit 2010. Next time will be at SweNug (Sweden .Net User Group). I decided to write a blog post about of some stuffs I was talking about.

    Users are a terrible thing! Protect your self from them

    ”Human users have a gift for doing the worst possible thing at the worst possible time.” – Michael T. Nygard, Release It!

    The kind of users Michael T. Nygard are talking about is the users of a system. We also have users that uses our code, the users I’m going to focus on is the users of our code. Me and you and another developers.

    “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler

    Good programmers also writes code that humans know how to use, good programmers also make sure software behave in a predictable manner despise inputs or user actions.

    Design by Contract

    Design by Contract (DbC) is a way for us to make a contract between us (the code writer) and the users of our code. It’s about “If you give me this, I promise to give you this”. It’s not about business validations, that is something completely different that should be part of the domain model. DbC is to make sure the users of our code uses it in a correct way, and that we can rely on the contract and write code in a way where we know that the users will follow the contract. It will make it much easier for us to write code with a contract specified. Something like the following code is something we may see often:

    public void DoSomething(Object value)
    {
       value.DoIKnowThatICanDoThis();
    }

    Where “value” can be uses directly or passed to other methods and later be used. What some of us can easily forget here is that the “value” can be “null”. We will probably not passing a null value, but someone else that uses our code maybe will do it. I think most of you (including me) have passed “null” into a method because you don’t know if the argument need to be specified to a valid value etc. I bet most of you also have got the “Null reference exception”. Sometimes this “Null reference exception” can be hard and take time to fix, because we need to search among our code to see where the “null” value was passed in etc. Wouldn’t it be much better if we can as early as possible specify that the value can’t not be null, so the users of our code also know it when the users starts to use our code, and before run time execution of the code? This is where DbC comes into the picture. We can use DbC to specify what we need, and by doing so we can rely on the contract when we write our code. So the code above can actually use the DoIKnowThatICanDoThis() method on the value object without being worried that the “value” can be null. The contract between the users of the code and us writing the code, says that the “value” can’t be null.

    Pre- and Postconditions

    When working with DbC we are specifying pre- and postconditions.  Precondition is a condition that should be met before a query or command is executed. An example of a precondition is: “The Value argument of the method can’t be null”, and we make sure the “value” isn’t null before the method is called. Postcondition is a condition that should be met when a command or query is completed, a postcondition will make sure the result is correct. An example of a postconditon is “The method will return a list with at least 1 item”.

    Commands an Quires


    When using DbC, we need to know what a Command and a Query is, because some principles that can be good to follow are based on commands and queries. A Command is something that will not return anything, like the SQL’s CREATE, UPDATE and DELETE.

    image

    There are two kinds of Commands when using DbC, the Creation commands (for example a Constructor), and Others. Others can for example be a Command to add a value to a list, remove or update a value etc.

    //Creation commands
    
    public Stack(int size)
    
    //Other commands
    
    public void Push(object value);
    
    public void Remove();

    A Query, is something that will return something, for example an Attribute, Property or a Function, like the SQL’s SELECT.

    image

    There are two kinds of Queries, the Basic Queries  (Quires that aren’t based on another queries), and the Derived Queries, queries that is based on another queries. Here is an example of queries of a Stack:

    //Basic Queries
            
    public int Count;
    
    public object this[int index] { get; }
    
    //Derived Queries
    
    //Is related to Count Query
    public bool IsEmpty()
    {
          return Count == 0;
    }

    To understand about some principles that are good to follow when using DbC, we need to know about the Commands and different Queries.

    The 6 Principles

    When working with DbC, it’s advisable to follow some principles to make it easier to define and use contracts. The following DbC principles are:

    1. Separate commands and queries.
    2. Separate basic queries from derived queries.
    3. For each derived query, write a postcondition that specifies what result will be returned, in terms of one or more basic queries.
    4. For each command, write a postcondition that specifies the value of every basic query.
    5. For every query and command, decide on a suitable precondition.
    6. Write invariants to define unchanging properties of objects.


    Before I will write about each of them I want you to now that I’m going to use .Net 4.0 Code Contract. I will in the rest of the post uses a simple Stack (Yes I know, .Net already have a Stack class) to give you the basic understanding about using DbC. A Stack is a data structure where the last item in, will be the first item out. Here is a basic implementation of a Stack where not contract is specified yet:

    public class Stack
    {
        private object[] _array;
    
        //Basic Queries
        
        public uint Count;
    
        public object this[uint index]
        {
          get { return _array[index]; }
          set { _array[index] = value; }
        }
    
        //Derived Queries
    
        //Is related to Count Query
        public bool IsEmpty()
        {
          return Count == 0;
        }
    
        //Is related to Count and this[] Query
        public object Top()
        {
          return this[Count];
        }
    
        //Creation commands
    
        public Stack(uint size)
        {
           Count = 0;
           _array = new object[size];
        }
    
        //Other commands
    
        public void Push(object value)
        {
          this[++Count] = value;
        }
    
        public void Remove()
        {
          this[Count] = null;
          Count--;
        }
    }

    Note: The Stack is implemented in a way to demonstrate the use of Code Contract in a simple way, the implementation may not look like how you would implement it, so don’t think this is the perfect Stack implementation, only used for demonstration.

    Before I will go deeper into the principles I will simply mention how we can use the .Net Code Contract.

    I mention before about pre- and postcondition, is about “Require” something and to “Ensure” something. When using Code Contract, we will use a static class called “Contract” and is located in he “System.Diagnostics.Contracts” namespace. The contract must be specified at the top or our member statement block. To specify a precondition with Code Contract we uses the Contract.Requires method, and to specify a postcondition, we uses the Contract.Ensure method. Here is an example where both a pre- and postcondition are used:

    public object Top()
    {
         Contract.Requires(Count > 0, "Stack is empty");
         Contract.Ensures(Contract.Result<object>() == this[Count]);
    
         return this[Count];
    }

    The contract above requires that the Count is greater than 0, if not we can’t get the item at the Top of a Stack. We also Ensures that the results (By using the Contract.Result method, we can specify a postcondition that will check if the value returned from a method is correct) of the Top query is equal to this[Count].

    1. Separate Commands and Queries

    When working with DbC, it’s important to separate Command and Quires. A method should either be a command that performs an Action, or returning information to the caller, not both. By asking a question the answer shouldn’t be changed. The following is an example of a Command and a Query of a Stack:

    public void Push(object value)
    
    public object Top()

     

     

     

    The Push is a command and will not return anything, just add a value to the Stack, the Top is a query to get the item at the top of the stack.

    2. Separate basic queries from derived queries


    There are two different kinds of queries,  the basic queries that doesn’t rely on another queries, and derived queries that uses a basic query. The “Separate basic queries from derived queries” principle is about about that derived queries can be specified in terms of basic queries. So this principles is more about recognizing that a query is a derived query or a basic query. It will then make is much easier to follow the other principles. The following code shows a basic query and a derived query:

    //Basic Queries
            
    public uint Count;
    
    //Derived Queries
    
    //Is related to Count Query
    public bool IsEmpty()
    {
          return Count == 0;
    }

    We can see that IsEmpty will use the Count query, and that makes the IsEmpty a Derived query.

    3. For each derived query, write a postcondition that specifies what result will be returned, in terms of one or more basic queries.

    When the derived query is recognize we can follow the 3ed principle. For each derived query, we can create a postcondition that specifies what result our derived query will return in terms of one or more basic queries. Remember that DbC is about contracts between the users of the code and us writing the code. So we can’t use demand that the users will pass in a valid value, we must also ensure that we will give the users what the users wants, when the user is following our contract. The IsEmpty query of the Stack will use a Count query and that will make the IsEmpty a Derived query, so we should now write a postcondition that specified what results will be returned, in terms of using a basic query and in this case the Count query,

    //Basic Queries
            
    public uint Count;
    
    //Derived Queries
    
    public bool IsEmpty()
    {
        Contract.Ensures(Contract.Result<bool>() == (Count == 0));
    
        return Count == 0;
    }

    The Contract.Ensures is used to create a postcondition. The above code will make sure that the results of the IsEmpty (by using the Contract.Result to get the result of the IsEmpty method) is correct, that will say that the IsEmpty will be either true or false based on Count is equal to 0 or not. The postcondition are using a basic query, so the IsEmpty is now following the 3ed principle. We also have another Derived Query, the Top query, it will also need a postcondition and it uses all basic queries. The Result of the Top method must be the same value as the this[] query returns.

    //Basic Queries
    
    public uint Count;
    
    public object this[uint index]
    {
         get  { return _array[index]; }
         set  { _array[index] = value; }
    }
    
    //Derived Queries
    
    //Is related to Count and this[] Query
    public object Top()
    {
         Contract.Ensures(Contract.Result<object>() == this[Count]);
    
          return this[Count];
    }

    4. For each command, write a postcondition that specifies the value of every basic query.

    For each command we will create a postconditon that specifies the value of basic queries. If we look at the Stack implementation we will have three Commands, one Creation command, the Constructor, and two others commands, Push and Remove. Those commands need a postcondition and they should include basic query to follow the 4th principle.

    //Creation commands
    
    public Stack(uint size)
    {
    Contract.Ensures(Count == 0); Count = 0; _array = new object[size]; } //Other commands public void Push(object value) { Contract.Ensures(Count == Contract.OldValue<uint>(Count) + 1); Contract.Ensures(this[Count] == value); this[++Count] = value; } public void Remove() { Contract.Ensures(Count == Contract.OldValue<uint>(Count) - 1); this[Count] = null; Count--; }

    As you can see the Create command will Ensures that Count will be 0 when the Stack is created, when a Stack is created there shouldn’t be any items in the stack. The Push command will take a value and put it into the Stack, when an item is pushed into the Stack, the Count need to be increased to know the number of items added to the Stack, and we must also make sure the item is really added to the Stack. The postconditon of the Push method will make sure the that old value of the Count (by using the Contract.OldValue we can get the value a Query has before the method is called)  plus 1 will be equal to the Count query, this is the way we can ensure that the Push will increase the Count with one. We also make sure the this[] query will now contain the item we pushed into the Stack. The Remove method must make sure the Count is decreased by one when the top item is removed from the Stack. The Commands is now following the 4th principle, where each command now have a postcondition that used the value of basic queries.

    Note: The principle says every basic Query, the Remove only used one Query the Count, it’s because this command can’t use the this[] query because an item is removed, so the only way to make sure an item is removed is to just use the Count query, so the Remove will still follow the principle.

    5. For every query and command, decide on a suitable precondition.

    We have now focused only on postcondition, now time for some preconditons. The 5th principle is about deciding a suitable preconditon for every query and command. If we starts to look at one of our basic queries (will not go through all Queries and commands here, just some of them) the this[] query, we can’t pass an index that is lower then 1 (.Net arrays and list are zero based, but not the stack in this blog post ;)) and the index can’t be lesser than the number of items in the stack. So here we will need a preconditon.

    public object this[uint index]
    {
         get
         {
             Contract.Requires(index >= 1);
             Contract.Requires(index <= Count);
    
              return _array[index];
          }
    }

    Think about the Contract as an documentation about how to use the code in a correct way, so if the contract could be specified elsewhere (not part of the method body), we could simply write “return _array[index]” and there is no need to check if index is greater or lesser than Count, because that is specified in a “contract”. The implementation of Code Contract, requires that the contract is specified in the code. As a developer I would rather have this contract elsewhere (Like Spec#) or implemented in a way Eiffel uses it as part of the language.

    Now when we have looked at one Query, we can also look at one command, the Remove command (You can see the whole implementation of the Stack at the end of this blog post, where precondition is added to more queries and commands then what I’m going to show in this section). We can only Remove an item if the Count is greater than 0. So we can write a precondition that will require that Count must be greater than 0.

    public void Remove()
    {
       Contract.Requires(Count > 0);
       Contract.Ensures(Count == Contract.OldValue<uint>(Count) - 1);
    
       this[Count] = null;
       Count--;
    }

    6. Write invariants to define unchanging properties of objects.

    The last principle is about making sure the object are feeling great! This is done by using invariants. When using Code Contract we can specify invariants by adding a method with the attribute ContractInvariantMethod, the method must be private or public and can only contains calls to Contract.Invariant. To make sure the Stack feels great, the Stack must have 0 or more items, the Count can’t never be a negative value to make sure each command and queries can be used of the Stack. Here is our invariant for the Stack object:


    [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(Count >= 0); }

    Note: The ObjectInvariant method will be called every time after a Query or Commands is called.

    Here is the full example using Code Contract:

    public class Stack
    {
       private object[] _array;
    
       //Basic Queries
    
       public uint Count;
    
       public object this[uint index]
       {
         get
         {
            Contract.Requires(index >= 1);
            Contract.Requires(index <= Count);

    return _array[index]; } set { Contract.Requires(index >= 1); Contract.Requires(index <= Count); _array[index] = value; } } //Derived Queries //Is related to Count Query public bool IsEmpty() { Contract.Ensures(Contract.Result<bool>() == (Count == 0)); return Count == 0; } //Is related to Count and this[] Query public object Top() { Contract.Requires(Count > 0, "Stack is empty"); Contract.Ensures(Contract.Result<object>() == this[Count]); return this[Count]; } //Creation commands
    public Stack(uint size) { Contract.Requires(size > 0); Contract.Ensures(Count == 0); Count = 0; _array = new object[size]; } //Other commands public void Push(object value) { Contract.Requires(value != null); Contract.Ensures(Count == Contract.OldValue<uint>(Count) + 1); Contract.Ensures(this[Count] == value); this[++Count] = value; } public void Remove() { Contract.Requires(Count > 0); Contract.Ensures(Count == Contract.OldValue<uint>(Count) - 1); this[Count] = null; Count--; } [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(Count >= 0); } }


    Summary


    By using Design By Contract we can make sure the users are using our code in a correct way, and we must also make sure the users will get the expected results when they uses our code. This can be done by specifying contracts. To make it easy to use Design By Contract, some principles may be good to follow like the separation of commands an queries. With .Net 4.0 we can use the Code Contract feature to specify contracts.

    Read more...

  • The Aspen progress – Silverlight 4, Net 4, WCF RIA Services ref. project

    It was a while since I wrote a blog post, the reason are many, first preparation for the SDC2010 conference where I talked about WCF RIA Services, then 2 sessions at Microsoft TechDays 2010 where I talked about Web Form vs MVC and building business application with Silverlight 4, MVVM and WCF RIA Services.. and then bought a new car and also have bean on the Microsoft Visual Studio 2010 Ultimate tour and one week vacation in Italy. So a busy time. This blog post will only mention some of the latest updates we have made to the project.


    Data Model and Domain Model changes

    We still uses POCOs but we have removed the Code First feature because it’s not part of the EF 4.0 RTM. Instead Dag König have added the support of using T4 templates. So we create our entities out from our Data Model by using T4 POCO templates. You can find the template “AspenPocogeneration.tt”  in the project “Fdd.Aspen.DomainModel” and under the folder “Entities”.

    “Defensive programming/argument validations”


    Before we used methods to check if the user of the code passes in a correct value to our methods etc, now we have replaces it with Code Contract. The following is an example where we have for example used Code Contract:

    public BaseRepository(IObjectContext objectContext)
    {
          Contract.Requires(objectContext != null);
          Contract.Ensures(_objectContext != null);
          Contract.Ensures(_objectSet != null);
    
          _objectContext = objectContext;
          _objectSet = _objectContext.CreateObjectSet<TEntity>();
    }


    First we Requires that the objectContext attribute can’t be null, if it’s not null we will ensure the the private fields _objectContext and _objectSet will not be null. Code Contract is all about setting up a contract “if you give me this, I promise that you will get this.”. So by using pre-condition “Requires” we can check if the user of the code passes in the correct value we expected to get, then we use post-condition “Ensures” to make sure we fulfill our part of the contract. We also use Contract Invariant, to make sure the object is in a good state.


    [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(_objectContext != null); Contract.Invariant(_objectSet != null); }


    We haven’t upgraded all our code to use Code Contract yet,  but while we working with a old class we will do the changes, every new class will use Code Contract.

    ViewModel and the Client Side Data Channel

    At the moment there are no changes made to the client-side and ViewModel. We will not use a 3ed party framework or Prism etc, we will try to use most of the things shipped with the RTM version of Silverlight 4 and VS2010. I haven’t mention anything about the client-side in a blog post yet even if there are some test code added to try out some infrastructure stuffs. To make it easy to do the testing we will work with an abstraction of the server call. At the moment we call it a DataChannel but some people also call it “Repository” for the client-side. The name here is not so important.

    public class ListMemberViewModelDataChannel : IListMemberViewModelDataChannel
    {
        MemberDomainContext _memberDomainContext = new MemberDomainContext();
    
        public void GetAllMembersAsync(Action<IEnumerable<MemberPM>> getAllMembersCompletedCallBack)
        {
            _memberDomainContext.Load<MemberPM>(
                           _memberDomainContext.GetMembersQuery(),
                           loadOperation =>
                          {
                              getAllMembersCompletedCallBack(loadOperation.Entities);
                           }
                           , null);
       }
    
    
       public void Save()
       {
           _memberDomainContext.Save();
       }
    }

    The ListMemberViewModelDataChannel is the “DataChannel” for the ListMemberViewModel, it have the responsibility to handle all communication to the server-layer on the server-side. The DataChannel will use WCF RIA Services, and one DataChannel will be create for one View, and one DomainService will be used for one View. The reason why we use a “DataChannel”, is to make it easy to do testing against our ViewModel and also if we don’t want to use WCF RIA Services, we can simply implement a DataChannel that will use WCF.

    The following is an example of a ViewModel that uses a DataChannel:

    public class ListMemberViewModel : BaseViewModel
    {
        private ObservableCollection<MemberPM> _members = null;
        private IListMemberViewModelDataChannel _listMemberViewService;
    
        private bool _isBusy = false;
    
    
        public ListMemberViewModel(IListMemberViewModelDataChannel listMemberViewService)
        {
             Contract.Requires(listMemberViewService != null);
             Contract.Ensures(_listMemberViewService != null);
    
             this._listMemberViewService = listMemberViewService;
    
             this.IsBusy = true;
             this._listMemberViewService.GetAllMembersAsync(GetAllMembersCompleted);
         }
    
    
         private void GetAllMembersCompleted(IEnumerable<MemberPM> result)
         {
             this.Members = new ObservableCollection<MemberPM>(result);
             this.IsBusy = false;
         }
    
    
         public bool IsBusy
         {
            get { return _isBusy; }
            private set
            {
               _isBusy = value;
               base.NotifyPropertyChanged("IsBusy");
            }
         }
    
    
         public ObservableCollection<MemberPM> Members
         {
             get { return _members; }
             private set
             {
                _members = value;
                base.NotifyPropertyChanged("Members");
             }
          }
     }

    On the server-side in our DomainServices we don’t expose our DomainModel’s Domain entities, instead we create a “Presentation Model”, a model more suitable for presentation purpose. They will be part of the ViewModel, and thanks to the WCF RIA Services uses of the INotifyDataErrorInfo interface, we can use the “Presentation Model” as part of the ViewModel (it’s a ViewModel more or less in the way it’s implemented but with not operation added to it). We haven’t added the infrastructure for location our ViewModels and bind them to the Views yet, we are thinking about using MEF or Unity 2.0, or maybe combine both of them. At the moment we use simply hardcode the dependencies and do the injection manually in the View’s code-behind:

    public MainPage()
    {
         InitializeComponent();
    
         var listMemberViewModel = new ListMemberViewModel(new ListMemberViewModelDataChannel());
    
         this.DataContext = listMemberViewModel;
    }


    This will be changed, I’m thinking about using convention to locate the ViewModel for the View.

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

    Read more...

  • Some steps for moving WCF RIA Services Preveiw to the RC version.

    I moved the Aspen project from the WCF RIA Services VS2010 Preview to the RC version. Maybe some of you will move your Preview version to the RC, so I wrote down some steps..
     
     
    Server Side
     
    You can start with replacing the Web.Config, because I don’t know how your config looks like, I just copy a clean PDC preview config and paste it here and the new one for the RC
     

    Old one:
     
     
    <?xml version="1.0"?>
    <configuration>

        <system.web>
            <httpModules>
                <add name="DomainServiceModule" type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            </httpModules>
            <compilation debug="true" targetFramework="4.0" />
        </system.web>
        <system.webServer>
            <modules runAllManagedModulesForAllRequests="true">
                <add name="DomainServiceModule" preCondition="managedHandler"
                    type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            </modules>
            <validation validateIntegratedModeConfiguration="false" />
        </system.webServer>
     
        <system.serviceModel>
            <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
        </system.serviceModel>
    </configuration>
     
     
    New one:
     
     

    <configuration>
      <configSections>
        <sectionGroup name="system.serviceModel">
          <section name="domainServices" type="System.ServiceModel.DomainServices.Hosting.DomainServicesSection, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication" requirePermission="false" />
        </sectionGroup>
      </configSections>
     
      <system.web>
        <httpModules>
          <add name="DomainServiceModule" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </httpModules>
        <compilation debug="true" targetFramework="4.0" />
     
      </system.web>
     
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
        <modules runAllManagedModulesForAllRequests="true">
          <add name="DomainServiceModule" preCondition="managedHandler"
              type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </modules>
      </system.webServer>
     
      <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
     
     
    You can see all the changes by comparing both of them. I just made a simple copy and paste of the whole file in the Aspen project.
    On the server-side the following assembly references need to be replaced:
     
    Replace:
    System.Web.DomainServices
     
    To:
    System.ServiceModel.DomainServices.Server
     
    Located in the following folder (depends where your SDK is  installed):
    C:\Program Files\Microsoft SDKs\RIA Services\v1.0\Libraries\Server

    Then replace the System.Web.DomainServices namespace to System.ServiceModel.DomainServices.Server

    Replace the following assembly references:

    System.Web.Ria
    (and System.Web.Ria.Services)

    To:

    System.ServiceModel.DomainServices.Hosting
    System.ServiceModel.DomainServices.Server

    The EnableClientAttribute is located in the Hosting assembly now.

    Then replace the System.Web.Ria namespace to System.ServiceModel.DomainServices.Hosting.

    For the Invoke-, Insert,  IgnoreAttribute etc, replace the System.Web.Ria.Services namespace with System.ServiceModel.DomainServices.Server.
     
     
    Note: I don’t use LinqToEntitesDomainService, but I guess if you do, then you need on the server side add a reference to the assembly:
     
    System.ServiceModel.DomainServices.EntityFramework
     
    The LinqToEntitesDomainService is located in the following namespace: System.ServiceModel.DomainServices.EntityFramework
     
     
     
    Client-Side:
     
    Replace:

    System.Web.Ria

    To:

    System.ServiceModel.DomainServices.Client
    System.ServiceModel.DomainServices.Client.Web

    Located in the folder (depends where your SDK is installed):

    C:\Program Files\Microsoft SDKs\RIA Services\v1.0\Libraries\Silverlight

    Add a reference to the following assembly:

    System.ServiceModel.Web.Extensions

    (This assembly is not in the SDK folder; use the .NET Tab in the Add Ref. dialog)
    Remove the old “Generated_Code” folder and rebuild your solution.


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

  • WCF RIA Services Silverlight Business Application – Using ASP.NET SiteMap for Navigation

    Note: This blog post examples is based on the WCF RIA Services PDC Beta and WCF RIA Services VS 2010 Preview, changes to the framework may happen before it hits RTM.

    This blog post will be about using the ASP.NET SiteMap together with WCF RIA Services and the Navigation feature added to Silverlight. I assume you are familiar to how the Navigation feature will work when reading this blog post, even if you don’t know you may find this blog post interesting.

    Read more...

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