Kurser och utbildning av IT-proffs och systemutvecklare

i Sök

Cornerstones utvecklarblogg

Alla Taggar

All Tags » Design and Architecture   (RSS)
Sorry, but there are no more tags available to filter with.

  • MVC - Expression Language and custom tags

  • What Data Access technology do I recommend?

    I got several questions about what Data Access technology I recommend. So I decided to write down the answer into a post.
    First of all I use a "model-first" approach, which means that I don’t care about the data source. So what I do is first to create my domain model with entities, business logic etc. When the model is done I decide what data source I need to use. The result is often a database. Because I use Domain Driven Design, I also use OR-Mapper to map my model against a database. I don’t use DataSet, I actually never did when .Net arrived. The reason is that a DataSet is more or less a copy of a database. It has Tables, rows and columns. In .Net 1.x the DataSet was a huge object, in .Net 2.0 Microsoft reduce the size of it, but still it has a database like model. I also wanted to use the power of Object-Oriented programming and a DataSet in this case was not an option. I also wanted to make my code easier to read and understand. By using an object like Customer which will have information about a Customer is more logical for people to understand than having a DataSet with relations etc with the information about a customer.

    The OR-Mapper I used was my own implementation or nHibernate. But as soon as ADO.Net Entity Framework will arrive, I will probably use it instead of other OR-Mappers (The mapping tools and the final features of ADO.Net Entity Framework will decide if I will use of it.). One sad thing with the ADO.NET Entity Framework is the lack of support for POCOs (We need to implement an interface on all of our entities).

    Very soon we will have the possibility to use LINQ to SQL. I know that several people will use it for data access. With LINQ to SQL we can easily by dragging out tables get classes generated and can start using LINQ as a query language against the generated model to get our data. The problem is that the model is created out from a database schema, and a database schema is based on relations and normalization rules etc. So we can’t really generate a domain model out from a database, or we shouldn’t if we use Domain Driven Design. The design of our model should not be decided by the data source. But it’s a very fast technology if we want to speed up our data access development against a database. For small projects where a database is required or already exists from the beginning, I will probably use LINQ to SQL, but it depends on what the application should do. For large applications I will probably not use LINQ to SQL.

    With the ADO.Net Entity Framework we will be able to create our own model first and then map it against one or more data sources; we can also use Value objects etc. LINQ to SQL can’t map against several data sources and has the lacks or support for Value objects which I often use in my domain model.


    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Why I don't think you should try to reuse the IView and presenter for different UIs

    In this post I will talk more about the "MVP" pattern and why I don't think you should focus on building the IViews and Presenters to reuse them for other UIs.

    Some people try to create an IView (When I use the IView in this post, I’m talking all the view’s interface that a presenter will work against) and a presenter/controller (I will use the word presenter instead of a controller) that should be reusable for any kind of UI, for example Windows App and a Web based. My suggestion is not to focus too much on a common implementation of the IView and the presenter to make them reusable by other UIs when you create them, instead take advantage of the platform capability but use the Supervising Controller pattern to make it possible to test the complex logic. I will in this post try to explain why I don’t try to create IView and presenter that should be reusable between different kind of UI (When I’m talking about different kind of UI, I talk about Windows Forms and Web Form etc), and why I don’t think you should focus on a generic implementation. In some situations you can use some valuable patterns to solve some specific problems, that other UIs’ can’t reuse, or they can but it require extra solutions that can be complex to create. If you need to reuse some complex logic that is for example common for both a Web form and a Win form, make sure to refactoring them out from the presenter into a common classes and reuse that logic in different presenters,  instead of putting it into one presenter that you will try to reuse among several UIs.

    First of all let’s take a look at the Supervising Controller. The main purpose of the pattern is for testability issues. We separate logic out from the view into the presenters/controllers. By doing this we can create unit tests that will test the logic. I think everyone agree on this. So by looking of the implementation of the Supervising Controller, we can see that we can sort of reuse the presenter and the IView for other UI as long as create a view that uses or IView interface.

    Here is what Martin Fowler writes about the Supervising Controller:

    “The essence of a good Supervising Controller is to do as little as possible. Let the view handle as much as possible and only step in when there's more complex logic involved.”

    As long as we can rely on simple views in our different UIs, we can sort of reuse the IVIews and the presenters/controllers. But we also need to have very good knowledge about the different UIs, and can also identify the common denominator of the different UIs. The common denominator can decrease when the abstractions of the UIs increases (I will talk more about later). If we only focus on the complex logic and add it to the presenter and also use what the UI can offer us, we can reduce the complexity in some situation and make it easier to reuse the presenter and IView. But still we can face several problems. If we open up a child window, which should synchronize the data from the child window into the root window, how should we handle that in a generic way so it will work for all UIs? Or if we have several windows open and one changes in one window should reflect all the others to refresh them self.

    When we are working with the Supervising Controller we simply don’t want to put a dependency between the different views nor the presenters/controllers. The reason is that each presenter should only know about one view (which it is a presenter for); a view should only be bind to one presenter. If we now have an app with a root view and a child view, for example a root view opens a child view which should give the root view some data back. Let’s assume we want to reuse the child view for other views, in that case we don’t want the two views to have a dependency to each other (We don’t want the child to know about the root, we don’t want the root to know about the child). There are two patterns that can be used to transfer data from one view to another, the Flow Synchronization and the Observer Synchronization. We probably don’t want to use the Flow Synchronization pattern for this, the reason is that Flow Synchronization is a pattern for make sure a view will update itself when other views state is changed and the changes should be shared across views in the applications. This will sort of couple every view to another view in an application, and changes in one view (implementation changes) can lead to several changes in other views because of the coupling, this can be messy and hard to maintain. Another solution for sharing data between views is by using the Observer Synchronization pattern. In that case we use events on the model object that we can subscribe to. So if the state of the model object is changed, we can make sure each view that uses that model object can update itself. The Observer Synchronization pattern will remove the coupling between views. If we use the Observer Synchronization patterns together with the Supervising Controller, the Observer should be in the presenter/controller. By using this pattern the model object need to trigger an event when the state of the object is changed, by doing so, the presenters/controllers that need to know when the changes take place, can simply subscribe to the model object’s event. For example:

    public delegate void DomainChangeHandler(object sender, EventArgs e);

    public class Customer
    {
         public event DomainChangeHandler StateIsChanged;

         ...
         public string FirstName
         {
             set
             {
                ...
                StateIsChanged();
             }
         }
    }

    Note: Because each domain object would probably use the StateIsChanged event, we could use the Layer Supertype to put the event into the Supertype (base class).

    The presenter can now hook up to the Customer’s SateIsChanged event and for example perform a refresh of the view:

    public class CustomerViewPresenter
    {
       ...
       private Customer _customer; 

       public CustomerViewPresenter(Customer customer)
       {
           this._customer  += new DomainChangeHandler(Customer_Changed);   
       }

        public void Customer_Changed(object source, EventArgs e)
        {
            //refresh the view
        }
    }

    Note: The Customer is passed as an argument to the constructor to the Presenter, it’s because we need to have the Customer in the applications state, so each view that want to display the customer, uses the same instance. We could have created some kind of an Identity Map, where we could get the customer from; in that case we don’t need to pass the Customer into the presenter. But I will make the code easy to read and make it small in this post.

    Now if any other presenter would change the customer, the Customer_Changed method of the CustomerViewPresenter would be called and make sure the presenter update the view with the new information. As you can see, this will make it difficult to use in a Web based app, where the protocol we use is a request/response. It works great in Window Form applications because it’s not stateless like a web app.

    As you can see the presenter that is created above will not work very well in a Web based application (remember a Web From is disconnected from the server after the page is processed and we got the response). As you may know, a server-side event will not notify the client, so in this case the presenters can’t tell the different web forms to update them self . It can sort of be solved, but it’s not easy all time and can be difficult to maintain. For example we can use a poller from the views that will ask the server for any changes in the model objects. The problem with this solution is that we need to have all the opened web forms’ presenters in the state on the server if we use the Observer Synchronization and want to know when a model object state is changed. One problem we will face here is the way to find a solution to release the presenter from the sate and also the subscription of the events when the web from is closed on the client, if not, we can have memory leaks. This can for example be done by have some kind of a time window, so if the poller hasn’t asked for any changes after a specified time, the presenter will be released. But is it worth the time and effort to even try doing something that will make the Web From behave like the Win form in this case? If we are going to build more AJAX enabled web sites, we will put more logic to the client-side, if we will use Silverlight, we also add more logic on the client-side, for example when a button is pressed on the client-side we can do an asynchronous call to a service to get data that should fill the view with information. So in this case we can’t reuse the same presenter and IVIew we created for the Windows application, we need to have two different implementations of the presenter and IView. AJAX and Silverlight abstracts the complexity of writing rich web based clients, and with this new abstraction we need to move the view and presenter up to the client-side.
     
    Martin Fowler writes the following about the Observer Synchronization pattern:

    “Web user interfaces are effectively a sequence of screens, this is an example where the protocol of the client/server connection makes Observer Synchronization very difficult to do.”

    Let’s assume we have a Windows form with checkboxes, each checkbox represents a color. When a user selects one checkbox we will trigger an event that will automatically set a background color of the window to the selected color, here is an example:

    Form:

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
                this._presenter.SetBackGroundColor(Color.blue);
    }

    Presenter:

    public SetBackGroundColor(Color color)
    {
          this._view.BackGroundColor = color;
    }

    IView:

    Public interface IMyView
    {
         Color BackGroundColor {get; set;}
    }

    View:

    public class MyView : IMyView
    {

        public Color BackGroundColor
        {
            get { return this.BackColor; }
            set { this.BackColor = value; }
        }
    }

    Note: Don’t hang up to this example; I only use it for demonstration purpose and use the simplest scenario that popped in my mind.

    As you can see, we can theoretically easy reuse both the IMyView and the Presenter for another UI, for example a Web form.  The problem here is that we need to make a postback when we select a checkbox only to set the background color of the window. So is it worth another roundtrip to the server, it will affect the performance of our app. Most developers would probably not want the extra roundtrip, so instead they use a client-side script that will do the work (set the color dynamically). As you may know, AJAX is a solution that almost every web developer is using to increase the user experience and create rich clients. So in this case the reuse will only make the app clumsier. But back again to what Martin Fowler wrote:

    “The essence of a good Supervising Controller is to do as little as possible. Let the view handle as much as possible and only step in when there's more complex logic involved. One of the prime reasons to use Supervising Controller is for testability. Assuming the view is hard to test, by moving any complex logic into the controller, we put the logic in a place that's easier to test.”

    So in this case, the logic is not complex, it easy logic. So in the Windows form app, we can still use events because it’s the common way when we build Win Forms, but in a web based app, we will probably use client-side script, and try to avoid the extra run trip to the server. There are several other similar issues where we don’t want to do a roundtrip to affect the performance or the user experience only to reuse an IView and a presenter.

    We should use what the UI can offer us (“let the view handle as much as possible”), and put complex logic that we need to test into the presenter (“by moving any complex logic into the controller, we put the logic in a place that's easier to test.”). This can of course left out some code for automation testing.  But I think it’s more important to create UI that is easy to use and also increase user experience, than testing everything with unit tests. The important thing is that the tests cover the complex logic, which will be located in the presenter. In this case other tests during the development will cover the UI specific code.

    Conclusion

    Have this in mind to build a Windows application is not the same as building a stateless and request/respond application. To make it possible we need to find the common denominator between the UIs, which can reduce the capability to a user friendly application and set limit to how we can create our UI. We can for some UIs create an IView and a presenter that will work for the different UIs, but we will probably spend time on new solutions to make it possible to reuse (For example if we use the Observation Synchronization pattern, which is easy to use in a Windows application but not in a Web based application, to make it work and to refresh the views after the state has been changed, we need create a new solution). If we try to build a IView and presenter that should be used for both Windows app and Web Form, we must also have in mind that more and more want the web application to be richer and more user friendly. We have new way of building rich web apps by using AJAX and Silverligth, both work on the client-side, and we can for example do asynchronous call to a service over the network to get the data which should fill the view with information. So in this case we need to put an IView and presenter on the client-side. So my last advice is to not focus on creating a reusable IView and presenter for different platforms, instead create it for the current targeting platform.  If anyone doesn’t agree with me, I’m really interested in hearing about your thoughts etc, and you are all welcome to try to persuade me about that I have wrong. But it will probably not be easy, but I will let the door be open ;)



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Is the use of Repositories a proof of using Domain Driven Design?

    After I listen to a podcast made by Ron Jacobs and with Jefferey Palermo, and also after looking at other people’s design and ideas and questions etc. I notice that some developers think they use Domain Driven Design (DDD) because they use an OR-mapper, they use entities, and they use Repositories etc. I’m not alone, even Patrik Löwendahl has notice similar things and you can find his answer to a question by clicking here.

    I can create an app today that uses an object that for example reflects a Customer, I could also separate the logic about how to fill the Customer with data out from the entity into separate classes (for example creating a class and name it CustomerRepository the will give me a Customer). By doing this I have code like this:

    Customer customer = CustomerRepository.GetCustomerByNo(“1000”);

    Because I have created an entity Customer and a “Repository” class, it doesn’t mean that I use DDD. This is a common way of writing applications; but some people use the word Manager instead of Repositories etc.  The reason some developers use this approached instead of using ActiveRecord [PoEAA], is to separate the logic of doing a “data access” from the entity. Some developers use the Active Record pattern and like it. For about two years ago I helped a company applying part of DDD. Some month later he asked me a question about aggregate and sends me some example code. When I look at the code I see this:

    customer.Save();

    A typical Active Record pattern. I asked him why he doesn’t want to separate the way of saving the Order into a separate class. His respond was “I like this way better, for me it’s easier to understand and I think this kind of design is obvious in my application”. Then he told me “If you was the customer, would you like to let someone else put your cloth on or off?”. He wanted to give the responsibility of letting the Customer decide how he want to put the cloth on or off, not letting another one doing it for him, “Object thinking”. In this situation a friend of mine should probably reply:  “should the customer take a photo of himself?”  Even if he uses the Active Record pattern, he still uses DDD (I convince my friend to separate the data access logic from the entities). But what I will get to is that DDD has nothing to do with Repositories etc. DDD is a way of thinking and is a help to minimize the gap and misunderstanding between the business “activity” and the developer, make them get together closer to maximize the understanding of each other.  From the customer’s needs and business, we create a model together with the customer where we use the same language, so both understand each other “Ubiquitous Language”. This model is what the customer sees; this model is what the developers will turn into code by using object-oriented techniques and different patterns and practices etc. What Evans do in his book about DDD, is to give us his ideas of how we can turn the model we have created together with a domain-expert into code, based on what he notice is a good way to solve the problem of dealing with complicated domains. If a developer use the Evans patterns of using Repositories and create entities, is not even sure the developer uses DDD, because a developer can still use similar patterns for filling and getting entities in the applications. The domain-model we turned into code, by using entities etc, should not pay any attention or concerns about how we should get the data in the first place. It’s more important that we understand the domain-expert and can turn the domain-model into code, than focus on the implementation of the data-access.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Why is abstraction good?

    Let’s look at ALL developers around the world. What are the average developers good at? Writing solutions, right!? So what should developers do, of course they should do what they can do best, write solutions. The most common developers write business solutions that should solve a business need(s). Some few developers write frameworks etc and I will not include them in the word “developers” in this post, those developers are the people that will help the average developers to focus on what they do best. If developers (I will now on use the word “Developer” for “average developers”) are good at writing solutions I think they should do that, don’t you think? They shouldn’t focus and spend time on the infrastructure; they should instead do what they do best, let someone else focus on the infrastructure, people that are good at it. So developers should focus more on the conceptual level instead of the logical level. If we look at Domain Driven Design, we shouldn’t care about how data should be saved, we should instead focus on the domain-model. Most developers today are used to draw conceptual models, the logical way to do things that people will understand, is to try to reflect the real world when building applications. Try to think as an object not as a computer. What some developers have problem with is to map the conceptual model they have created to an underlying data source. Some mistakes many developers do is to create the database first and then the design of application. They let the data source drive the development. Sometimes developers don’t have a choice, the companies already has a database, but why care about it when you design your application, don’t design your app after a database. Instead create your conceptual model and let the administrators of the database instead care about the underlying data source and how to map it to your conceptual model. To make this possible we need a higher level of abstraction. If we look at a data-centric application, we will now with ADO.Net Entity framework (will be shipped during next year “2008”) have a tool where we can now focus on the conceptual model and create our business entities like “customer, product” etc. Developers don’t even need care about how the underlying data source looks like. They don’t even need to care about how the data is saved, where it’s saved etc. They only make sure to change the data by working against the business entities they have created, search for the data they need, but by asking the conceptual model. No need to write SQL, no need to map the data returned from the data source to the conceptual model. We already have this kind of mapping solutions for many years back in time, the OR-Mappers. What does all this have to do with abstraction and my title of the post. Well to make sure developers focus on what they are good at, abstraction is needed. But how far can we abstract things. Look at OLE DB, it was an abstraction to make it easier to get data from a database, later we got ADO and ADO.Net, another level of abstraction to make it easier to do save and get data from the database. Now we will soon have the ADO.Net Entity Framework. Well even if developers will get the Entity Framework, they will ask more abstraction, they want to make sure things will be simpler all the time. Is this because developers are lazy people!? Well abstraction is good; because it will make sure developers do what they are good at.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Process-orientation and dynamic applications

    I have during a long time build some kind of “static” applications; I have used Domain Driven Design for most of my solutions during the last three years. Most of those apps became static. During the last year now I have spend some time on Process-Orientation (PO). As you may know a company has several of process. To simplify the process they sometime want to replace some processes or part of a process with a software of some kind. Most of those apps became static. They need to go in and change the app if the process needs to be changed. This could even result that the old app is not good enough and a whole new one need to be build. The whole process will cost company money. Sometimes I don’t even think they get the money back by simplifying the process, especially not if the use a static application. So I (not only I) have notice that more and more company want to minimize the cost of building or changing an app based on changes in the business (for example when a process is changing). So what I think we need is to be more process-oriented. Look at the process, build activities for the process. The activities is something developer can help companies with, the process-schema itself can often be created by the company, for example using BPML. So the new focus for developers will be to create “activities”. Those activities are often small, but can be complex. But if an activity will became complex to build, we should see if we can solve it by creating an inner process instead that can be used. If not, we can apply for example DDD when we create the activity, either as a service or a static component. I think the important thing is to make new applications dynamic, at least as much as possible. If they need new activities (which I think should be created as re-useable units if possible) they get some help of creating them. Here is the developers’ role. I saw a large process-schema written after the BPML, and the activities were really small. The process that was created should replace an “errand managing system”. Instead of using a static application as an “errand managing system”, they draw processes.  It was really cool. If a process changed, the company simply changed the schema and hit save and run button, and the process-engine run the process after the new schema. If they need a new process in the company to solve some problems, they simply draw the process. There was no need to go in and change a static app, and deploy it. Can it be more dynamic!? Together with PO, I can see a great use of SOA, where the activity in a process is a “call” to a service. Today we have a relative great process-engine, and that is the Microsoft Workflow Foundation, what we don’t have is a great designer for companies that follow a standard like BPML to create the process yet (But support for BPEL exists). But we can create one and use the WF compiler with the XML file that defines the process; we can also help the company as long as they provide us with some kind of schema and then use the WF designer integrated into Visual Studio.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • SweNug Architect Summit 2007 - Best ever for Architects ;)

    I am going to let all my Swedish readers to know that SweNug (Sweden .Net User Group) are going to have the second Architect Summit. It was about two years ago where people around Sweden got together and talked two day about everything regarding Architecture, Models and Design etc, such as Agile, SOA, Domain Driven Design (DDD), Test Driven Development (TDD) etc. Dag König, Jonas Ekström, Daniel Akenine from Microsoft and Jimmy Nilsson from Factor10 was some of the people that was at the summit.  The best thing with SweNug Architect Summit, is that we use Open Spaces, so everyone that will attend can put an interesting topic on the agenda and people that are interested in that topic will get together and talk about it. So no speakers no pre-defined agenda, it’s you who decide the topics.The second best thing is “IT’s FREE, will not cost anything to attend. The Architect Summit is a good place to meet new people, to share experience and problems with each other, to learn about new interesting things etc. This will take place somewhere after the summer this year (2007), the date is not yet set, but this post is about to let you know that the Summit will take place this year so you can be prepared for the best architecture event ever in Sweden ;)

    If you are interested and have some questions, please don’t hesitate to contact one of the arranger of the SweNug Architect Summit this year, and we are:

    Fredrik Normén

    Patrik Löwendahl

    Ps. because we use Open Spaces we only have a limit of seats, so be on your watch for the date and time.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • My point of view about using sprocs.

    My college Patrik Löwendahl wrote an interesting post about why he avoids sprocs. I would like to add my point of view on this.

    There are several cases where a sproc can be usefull, for example if the underlaying datasource must somwehow be changed, we could simple change the sproc as long as the changes don’t affect how our apps wroks. By changing the sproc we don’t need to compile the application that uses it. But one problem here is if someone re-use the sproc. In this case we need to have well defined tests and also run all tests for ALL applications to see that our changes in the sproc will not made other apps fails. But this is more in a perfect world where everyone have defined a test, in some cases we don’t even have that luxury and we need to search in every possible code to see which code uses the sproc I need to change. Well if we some sort of repository where ALL code is located we can search for it in the repository, but maybe the some code aren’t located in the repository, in that case we will have a problem. So why re-use sproc? Well, don’t! ;) Well if we should have versioning support for our sproc this should probably not be a problem, but we don’t have versioning. In one of Patrik’s post Mats Helander wrote an interesting comment:

    “Try to version sprocs and the dependency between them, you will certainly die of old age before you figure it out.

    Mats also add the following comment to Patrik’s post:

    “For example: I create a .Net component that uses Patrik's method to send sql to the db. Then I create a new version of the component with a new version of the sql. I can now use .Net versioning to select component and thereby version of the sql.”

    He has a good point here, but can’t this make our code bloated with several components because of some changes need to be done to our SQL? Maybe the changes to the SQL don’t event change the way or apps will behave. In this case I think sproc can be useful, but as long as I can be 100% sure that the sproc will NOT break the applications that will use it. But if we need to use versioning, we don’t have a good solution for this when we use sprocs, so in this case Mats comment is good.

    I moved away from sprocs for a long time ago and use OR-mappers that generate the SQL for me instead. Often when the underlying data source needed to be changed, the apps works because the mapping against the relational database was defined in a separate XML file, and the query I wrote was against my entity objects properties, not the fields and tables in the database. The first OR-Mapper I used (I wrote it by myself), I add the mapping as attributes to my entity object. The problem with this was that if the underlying data source changed, I need to open my entities and change the mapping and recompile my application. Most case when a we do a underlying changes in the data source, it’s a changed in our application, so in that cases the recompilation is needed anyway.

    One problem with “ad-hoc” quires is that we will not get a compilation error if the quires were written in a way that it would not work. But why not test the query first to see if it works in the Query Analyzer? Well some quires can be tested but some can’t’. For example if we need to use several of conditions that should generate our queries. We will have LINQ in the future that will and can solve this problem. We can define a query that will at compile time fail if it’s created wrong. The thing that generated “ad-hoc” is a problem and we will first at runtime notice it, is not really true. If we write test that will test them during the development we can make sure they will work. But can we write tests that test all different conditions that can be used if we need to generate our query!?

    I can’t say that I will NEVER use sprocs, it’s more a decision that I will make when I see what kind of project I should build etc. But mostly I will try avoiding sprocs, and because the OR-Mapper will generate the SQL for me I don’t really need to use sprocs. Well this was my point of why about this.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Model View Presenter - Update and problem.

    Based on some issues while I tried to update a post in my blog, I had to remove the whole post, which also includes the comments :(

     

    I got one very good comment from Tomas (Don’t know who he is ;)). In my first post about the MVP pattern I mentioned that I have the Save and Delete methods specified in the View interface:

     

    public interface INewsView : IView
    {
         int NewsID { get; }

         string NewsTitle { get; set; }

         string Body { get; set; }

         bool Display { get; set; }

         void SaveNews();

         void DeleteNews();
    }

     

    The bad thing with that solution is that the methods will be public, so the controllers can also make a call to them:

     

     public class NewsController : ViewController, INewsController
    {
            private const int NO_ID = -1;
           
            private INewsRepository _newsRepository;


            public NewsController(IView view) : base(view)
            {
                this._newsRepository = new NewsRepository();
            }

            private void Save()

            {

                   this.NewsView.SaveNews();  //Stack Overflow Exception

            }

     

            ...

    }

     

    In that case it will create a circular call that will later throw a Stack overflow exception. The idea with the implementation was to make sure the Mock View’s can sort of “simulate” actions. If the “Action” method is added to the View interface, even the Mock View need to implement them and that make it easy to write tests like:

     

    myMockView.SaveView();

     

    Which will make a call to the Controller’s SaveNews method. The SaveView method, in my first example will be called by the OnClick event of the Save button. Now after the good notice from Tomas, they are removed. So to “simulate” the Click of a button, we need to add the Action’s to the Mock View instead. I would like to thank Tomas for his comments.



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • Model View Presenter - Use test against Views in ASP.Net part 2

    In this post I’m going to move on and extend the post I wrote about the MVP and the Supervising Controller pattern.

    When I create my ASP.Net apps, I often remove the code that will navigate to another page or save data into state into separated classes. In that case I make sure a separate class will instead handle the navigation and the state of my ASP.Net application.  For example if we have a button on my page that should Save a News and then navigate to another page, we should probably write something like this:

    protected void SaveButton_OnClick(object sender, EventArgs args)
    {
           //... Get the news  info from the view

          NewsRepository.Save(news);

           Response.Redirect(“listnews.aspx”);
    }

    There is simply nothing wrong with that. But instead of letting the View handle the update and also the navigation to a “fixed” URL, I move it into a separate class (I will refer to the class as a controller also to make you more confused ;)):

    protected void SaveButton_OnClick(object sender, EventArgs args)
    {
           //... Get the news  info from the view

          NewsController.SaveNews(news);

    }

     

    private string const LIST_NEWS = “listnews.aspx”;

    public static Save(News news)
    {

         NewsRepository.Save(news);

         HttpContext.Current.Response.Redirect(LIST_NEWS);
    }

    If I now want to change the flow of my app, I will not need to care about the code in the View, instead I handle the changes in my Controllers. Let’s assume I have several Views where I need to save news, all those Views should always navigate so the same View when the News is saved. If I put that code into my Views, I need to made changes in several Views if the flow of my app will be changed; now with the separation of the navigation etc into separated Controller, I only have one place to change the code.

    How should this be implemented into the Controllers I use in my post about the MVP – Supervising Controller pattern?

    Well, the answer is, we add the navigation into our controllers. So for example is we take a look at the NewsController’s SaveNews method, we can do the following to handle the navigation in our Controller:

    public void SaveNews()
    {
         this._newsRepository.Save(this.CreateNewsFromView());

         HttpContext.Current.Response.Redirect(LIST_NEWS);

    }

    But this will cause a problem when we start to run our tests against the View, because our tests will use the NewsController, and in this case we have code that will have a dependency to the System.Web namespace and try to call the Redirect method. If we want to reuse the NewsController for a Win Form, we also will have some problem because a Win Form should not do a redirect, it should open a new Win Form after the SaveNews method is called.  So we need to move the Redirect code out from our NewsController. We put it back into the View. But isn’t that be strange, we just moved it from the View into the controller and now we moved it back. The thing is that the View is the component that has the dependency to the System.Web namespace in a Web app, if we use Win Form app, the Win Form View will know about the Win Form namespaces. In our case we will still make sure the navigation is handled form the Controller, so what we need to do is to put the code that should call the Redirect method into the View:

    public  void ShowView(string view)
    {
          Response.Redirect(view);
    }

    And the controller will make a call to the View’s ShowView method:

    public void SaveNews()
    {
         this._newsRepository.Save(this.CreateNewsFromView());

         this.NewsView.ShowView(LIST _NEWS);

    }

    Still the navigation is handled by the Controller. If we use a Win Form, the ShowView will be added to each Win Form View, and the Win Form View will have the implementation that should display the Win Form View.

    Note: There is only one problem with the code above. In the code the controller have the name of the view, in this example it’s a constant with the value “listnews.aspx”. So what we need to do here is to make sure we pass the name of the view, and the ShowView method in the View will have the responsibility to use the name to get the correct View to show. If we use a Web application, we can for example use the web.config AppSettings section we can map the name of the view to the URL of the page:

    <appSettings>
         <add key=”ListNews” value=”listnews.aspx”/>
         
    </appSettings>

    The ShowView in the View of a Web app. would now look like:

    public void ShowView(string view)
    {
         HttpContext.Current.Response.Redirect(WebConfigurationManager.AppSettings[view]);
    }

    The best thing with this solution is that we can now easily change the URL of a specific view to another one by only changing the settings in the web.config file.

    At the beginning of this post I also mentioned that I move the State management out form the View into separated classes also. If we decide to save some state into the Session variables, we can’t directly call the Session object from our Controllers, because the Session object is not used in Win Form apps, and will also add a dependency to the Session variables in the Controllers. So we also need to make sure the View have the implementation of accessing the State management objects.

    public void SaveSate(string key, object value)
    {
           Session[key] = value;
    }

    public object GetSate(string key)
    {
           return Session[key];
    }

    In our controllers we can now use the following code to save the state:

    this.NewsView.SaveState(news.ID, news);

    and the following code to load the value out from the state:

    News news = this.NewsView.GetState(newsID) as News;

    To avoid adding the code for the ShowView, SaveState and GetSate into every single View, we can create a base class for our View. In a Web From we need to make sure it will inherit the Page object. I will call the new base class for the Views for View, and here is the implementation of the View base class and IView interface:

    public interface IView
    {
         IViewController Controller { get; set; }

         void ShowView(string view);

         object GetState(string key);

         void SaveState(string key, object value);

    }

    public class View : Page, IView
    {

        private IViewController _controller;

        public IViewController Controller
        {
            get { return this._controller; }
            set { this._controller = value; }
        }

        public void ShowView(string view)
        {
            HttpContext.Current.Response.Redirect(WebConfigurationManager.AppSettings[view]);
         }

         public object GetState(string key)
         {
           return HttpContext.Current.Session[key];
         }

         public void SaveState(string key, object value)
         {
            HttpContext.Current.Session[key] = value;
         }
    }

    Our Web Form View would now look like:

    public partial class _Default : View, INewsView

    {

     

        public int NewsID

        {

            get

            {

                int id;

     

                if (Int32.TryParse(Request.QueryString["ID"], out id))

                    return id;

                else

                    return -1;

            }

        }

     

        public string NewsTitle

        {

            get { return this.titleTextBox.Text; }

            set { this.titleTextBox.Text = value; }

        }

     

        public string Body

        {

            get { return this.bodyTextBox.Text; }

            set { this.bodyTextBox.Text = value; }

        }

     

        public bool Display

        {

            get { return this.dispalyCheckBox.Checked; }

            set { this.dispalyCheckBox.Checked = value; }

        }

     

        public _Default()

        {

            base.Controller = new NewsController(this);

        }

     

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

                base.Controller.LoadView();

        }

     

        protected void saveButton_Click(object sender, EventArgs e)

        {

            ((NewsController)base.Controller).SaveNews();

        }

       

        protected void deleteButton_Click(object sender, EventArgs e)

        {

            ((NewsController)base.Controller).DeleteNews();

        }

    }

     

    If we want to write our unit-test, we need to make sure our Mock View’s inherits the View base class also. But in this case we need to create a Test Double to avoid the dependency to the Page object.  So we create a base class for the Mock View that we will inherit instead of the View in the code above.

     

    public class MockView : IView

    {

            private Dictionary<string, object> _state = new Dictionary<string, object>();

     

            private IViewController _controller;

     

            public IViewController Controller

            {

                get { return this._controller; }

                set { this._controller = value; }

            }

     

            public void ShowView(string view)

            {

     

            }

     

            public object GetState(string key)

            {

                return this._state[key];

            }

     

            public void SaveState(string key, object value)

            {

                if (!this._state.ContainsKey(key))

                    this._state.Add(key, value);

                else

                    this._state[key] = value;

            }

     }

     

    You can download the source code for this post here.

     

    Summary

     

    We have now extended the Controllers to also handle navigation of the application and also handle the state.  In our web app. example we have put the URL to our View’s into the Web.coinfig, which will make it easier for us to replace the URL to a View if needed. If we want to we could now go further and extend the code with our own configuration section, where we could also not only specify the View to show, but also what Controller the view should use. In that case we don’t need care about the instantiate the controller on each view. For example:

     

    <views>

           <view name="News" path="news.aspx" Controller=”NewsController”/>

    </views>

     

    But this is implementation need another post ;)

     



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • GRASP Controller, Page Controller pattern and the Supervising Controller pattern

    I will try to give you my point of view regarding the GRASP Controller, Page Controller pattern and the Supervising Controller pattern.

    For the readers who don’t know what GRASP is, here is a very short description:

    GRASP stands for “General Responsibility Assignment Software Patterns”, and there are 9 GRASP patterns that help you with the “basic” aspect of OO design.
    Some of the 9 patterns are Controller, Creator, Low Coupling, Polymorphism etc.

    Most people are probably recognizing the GRASP Controller in the MVC pattern (Model View Controller). When some people talk about the MVC pattern in an ASP.Net application they refer to something similar to this:

    View: The .aspx page
    Controller: The code-behind (People will often see this as the GRASP Controller).
    Model: The business logic or other logic that the controller will make a call to and use.

    But for me this is more like the Page Controller Pattern, because we are still in the UI-Layer, and the GRASP Controller pattern belongs more into to the Application Layer (The GRASP Controller is the first object beyond the UI layer that receives and coordinates (”controls”) a system operation.). The rule of the Application Layer in a Domain Driven Design (DDD) is to keep it thin and it doesn’t contains any business rules, and should only coordinate tasks and delegate work to collaborations of domain objects in the Domain Layer.

    For example in an ASP.Net Web Form the GRASP Controller will get a message from the code-behind (in an ASP.Net app), and coordinate it to the right object that will do the work. The GRASP Controller will not do the work itself, only delegate the work.

    I can see that the name “controller” in different patterns can be confused and have different meanings in different context. In my post about the Supervising Controller, the Controller (maybe it should be Presenter to not confuse people ;)) will have the logic that is often put into the code-behind, only to separate the logic from the View and also make it possible to write unit-test to test the logic.

    So if we look at the GRASP Controller once again, it has the responsibility to delegate to another object that will do the work. In my post the Controller will not delegate (or it will to the Repository), but still it will do some work to prepare the presentation of the View and also be the “Presenter”, and is very close to the UI-layer and should not belong to the Application Layer (regarding to me), and the GRASP Controller should not have the responsibility to prepare and be a presenter.

    This is my way of see it and maybe I got it all wrong ;)



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • A framework to create a workflow for ASP.Net pages

    During this weekend I found my old 1.1 project for handling flows in web applications. The main idea of the project was to make it easy to create and change a flow of pages. For example if I want to start a workflow to create a user, I could specify the flow in the web.config like this:

    <workflow>

         <flow name=”CreateUser”>

             <view name=”AddUser” view=”adduser.aspx” controllerType=”...UserController”/>
             <view name=”ConfirmAddser” view=”confirmuser.aspx”.../>

         </flow>

    </workflow>

    The flow above will first show a view with a form to enter user information; the next step is to confirm the information before the user is saved. If I decided to create one more step in the flow, I could easy add it to the configuration file without changing any code in my app:

         <flow name=”CreateUser”>

             <view name=”AddUser” view=”adduser.aspx” controllerType=”...UserController”/>
             <view name=”AddUSerToRole” view=”addusertorole.aspx” .../>
             <view name=”ConfirmAddUser” view=”confirmuser.aspx” .../>

         </flow>

    To start a flow from a page I simply wrote:

    viewWorklow.Start(“CreateUser”);

    It will automatically redirect me to the first node in the flow with the name “CreateUser”. I could then in my controllers for each view move to the next step in my flow by calling the MoveNext method:

    viewWorkflow.MoveNext();

    If I wanted to jump to a specific step in the flow, I could pass the name of the view into a MoveTo method, for example in the flow above I maybe don’t want to add a user to a specific role at a specific circumstance.

    viewWorkFlow.MoveTo(“ConfirmAddUser”);

    If I wanted to start a flow within a flow, I have two way of doing that; the first one is in the configuration file by using the <executeFlow> element inside of a flow, or just call the ExecuteFlow method (The  different between the Start method and ExecuteFlow, is that the ExecuteFlow will keep the stat of the flow, the Start will be used to start a new “session” of a workflow.).

    <flow name=”CreateUser”>

      <view name=”AddUser” view=”adduser.aspx” controllerType=”...UserController”/>
      <executeFlow name=”AddUserToRole” />
      <view name=”ConfirmAddUser” view=”confirmuser.aspx” .../>

    </flow>

    <flow name=” AddUserToRole”>

      <view name=” AddUser” view=”addusertorole.aspx” .../>

    </flow>

    or

    viewWorkflow.ExecuteFlow(“AddUserToRole”);

    When the MoveNext method finds that the next node in the flow is a new workflow, it will start that flow and keep the state of the current view.

    With this framework I could easily create a flow and I could avoid changing any code in my app if I needed to change the flow. This framework uses controllers to separate the logic from the Views and also handle the navigation and state. By not using the MoveNext mehthod, this can still be used to automatically instantiate a controller for a View, instead of manually do it as I mentioned last in my post Model View Presenter - Use test against Views in ASP.Net part 2

    I’m thinking of cutting this out from my existing .Net 1.1 application, and make it as a separate project and convert it to .Net 2.0. Could this be something that you could use in your apps in that case?



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se
  • The Web Client Software Factory - A must for Web developers ;)

    In the last week I wrote about the MVP pattern and controllers etc, I also wrote about my old page workflow framework, it you want something similar and also want to use controllers/presenter then take a look at the Web Client Software Factory from the Patterns & Practices team. It will help you build really cool web apps. The Web Client Software Factory have a page flow Application Block that can be used  to create a page flow (similar to my framework, but the Page Flow Application Block use  .Net .3.0’s Workflow foundation and don’t support Shared transitions between different page flows.). But most of you probably already have .Net 3.0 installed so I will probably not convert my old .Net 1.x version of my Page workflow framework to .Net 2.0. About two years ago I was in a live meeting with the P&P team and my suggestion to the team was to add a page flow kind of solution, I mentioned about my workflow, and now they have added a similar solution, so at last they did it :)

    (Don’t even know if it was because of me, but I’m glad that they add it, even if it took two years ;))



    Computers Blogs - Blog Top Sites
    Bloggtoppen.se

Den här bloggen

Syndication