Home
  Latest posts
  My Writings
  My Code
  My Gallery
  About me
 
  rssfeed Syndication
 
Bloggtoppen.se
 
 
Links
  Cornerstone
  SweNug
 
Post categories
  misc (48)
  Architecture (21)
  C# (19)
  Asp.Net (2)
  Vb.Net (2)
  Training (7)
  Data (19)
  Events (40)
  Platform (2)
  Orcas (4)
  Updates (3)
  Methods (10)
  Tools (6)
  Announcements (14)
  Languages (1)
  Patterns (6)
  Opinions (11)
  Fun (3)
  Ineta (1)
  Opinion (0)
  Practices (2)
  WCF (5)
 
 
 
Patterns (6)
Microsoft opening up Thursday, September 11, 2008

The last year or so I've reflected over Microsoft becoming more open  to the community about their development process, recent examples being the Entity Framework opening their design process with a blog: http://blogs.msdn.com/efdesign/ outlining the design decisions they are thinking about and their solutions, also from the EF team; the council populated by industry leaders from the community to influence the development of EF (https://lowendahl.net/showShout.aspx?id=210 ).

And now the latest addition in Microsoft new open strategy, they are releasing the source code for the Enterprise Library 4.0 under  the open source friendly license MS-PL ( http://msdn.microsoft.com/en-us/library/cc512463.aspx ) on Code Plex: http://www.codeplex.com/entlib

This is really a cool development from Microsoft corp and I applaud their willingness to change and open up more to the community. More of that and the future will look very bright for developers on the .NET framework.

--

More on the announcement: http://www.infoq.com/news/2008/09/entlib-source

Leave a comment Comments (2)
 
Pattern Focus: Singelton v2.0 Wednesday, February 20, 2008

Other pattern focus posts:

Singelton is a well-used and commonly known pattern in the software development world. It's been around for a very long time and we are still using the same basic three or four rows of code to implement it over, over and over again. With some inspiration from one of my students on my LINQ course today I finally sat down and did something about it. Enter Singelton v2.0:

MyFactory factory1 = new StaticSingelton("initialization data");
MyFactory factory2 = new StaticSingelton("initialization data");

The two, factory1 and factory2, now shares the same instance of MyFactory. How did I do this? Read on to find out.

Inspired by Nullable I took on the task of creating a generic singelton class that wraps and manages the singelton instances for you. My first naive attempt look something like this:

    public class NaivSingelton
        where T: class, new()
    {
        private static T _instance;

        public T Instance {
            get {
                if (_instance == null)
                    _instance = new T();

                return _instance;
            }
        }

        public static implicit operator T(NaivSingelton value) {
            return value.Instance;
        }
    }

Which gave the simple and naive usage of:

MyFactory factory = new NaivSingelton();

However, that didn't satisfy me. I had a couple of more requirements. I wanted to change what the scope/context of the singelton should be. I also wanted be able to initialize the object with parameters and I wanted to be able to separate singelton instances based on what those parameters was. So utilizing some more generic code, the Activator class and a version of "Template Method" a simple base class took form:

 

 public abstract class Singelton
    {
        protected class KeyHolder {
            private object[] parameters;
            internal KeyHolder(object[] parameters)
            {                
                this.parameters = parameters;
            }

            public override bool Equals(object obj)
            {
                if (obj == null && parameters == null)
                    return true;
                else if (obj == null)
                    return false;
                
                if (!(obj is KeyHolder))
                    return false;


                object[] paramsToCompareWith = ((KeyHolder)obj).parameters;

                if (paramsToCompareWith.Length != parameters.Length)
                    return false;

                for (int index = 0; index < parameters.Length; index++)
                {
                    if (parameters[index] != paramsToCompareWith[index])
                        return false;
                }

                return true;                
            }

            public override int GetHashCode()
            {
                int hashCode = 0;

                foreach (var item in parameters)
                {
                    hashCode = hashCode ^ item.GetHashCode();
                }

                return hashCode;
            }
        }
        
        public Singelton() { }

        public Singelton(T initialObject)
        {
            StoredInstances[key] = initialObject;
        }

        public Singelton(params object[] initializationParameters)
        {
            InitializationParameters = initializationParameters;
        }
    
        private object[] _initializationParameters;
        private KeyHolder key = new KeyHolder(null);
         
        protected object[] InitializationParameters
        {
            get
            {
                return _initializationParameters;
            }
            set
            {
                _initializationParameters = value;
                key = new KeyHolder(value);
            }
        }

        protected abstract Dictionary StoredInstances { get; }

        public T Instance
        {
            get
            {
                if (!StoredInstances.ContainsKey(key))
                    StoredInstances[key] = CreateNewInstance();

                return StoredInstances[key];
            }
        }

        private T CreateNewInstance()
        {
            return (T)Activator.CreateInstance(typeof(T), InitializationParameters);
        }

        public static implicit operator T(Singelton value)
        {
            return value.Instance;
        }
    }

This now allowed me to create different types of singelton implementations that stored the singelton instances differently. Also using a dictionary and a separate Key class for that dictionary (thanks for the idea Roger) I was able to differentiate instances based on what initialization data that was passed to the constructor of the singelton class.

Now I could simply create new subclasses:

    public class ThreadStaticSingelton : Singelton
        where T : class
    {
        [ThreadStatic]
        private static Dictionary _storedInstances = new Dictionary();

        public ThreadStaticSingelton(T initialObject) : base(initialObject) { }
        public ThreadStaticSingelton(params object[] initializationParameters) : base(initializationParameters) { }


        protected override Dictionary StoredInstances
        {
            get
            {
                return _storedInstances;
            }            
        }
    }

And

public class StaticSingelton : Singelton
        where T : class
    {
        private static Dictionary _storedInstance = new Dictionary();
       
        public StaticSingelton(T initialObject) : base(initialObject) { }
        public StaticSingelton(params object[] initializationParameters) : base(initializationParameters) { }

        protected override Dictionary.KeyHolder, T> StoredInstances
        {
            get { return _storedInstance; }
        }
    }

Which gives me the possibility to initialize singeltons like this now:

 

            MessageClass m1 = new StaticSingelton("Hello {0}");
            m1.Say();

            MessageClass m2 = new StaticSingelton("Hello {0}");
            m2.Say();


            MessageClass m3 = new StaticSingelton("Hello 2 {0}");
            m3.Say();

            MessageClass m4 = new StaticSingelton("Hello 2 {0}");
            m4.Say();

M1 and M2 shares the same instance, while M3 and M4 shares another.

One could easily think about other possible singelton implementations that can easily extend the base singelton class and take advantage of the generic way in which it get's initialized.

You can download my example project over here: https://lowendahl.net/shoutCode.aspx

Leave a comment Comments (5)
 
Pattern Focus: Mediator Pattern Sunday, September 16, 2007

It has been a long time since my last "pattern focus" but I think I'm ready to pick it up again. This time I want to talk about the mediator pattern, the UN diplomat of patterns.

I have a funny history with this pattern. When I first used it I patted myself on my back really proud of the code design. By then I did not know that the implementation was a known pattern, I had just made sure that my implementation honored the Single Responsibility Principle (separation of concerns). the Liskov Substitution Principle and basic OO reuse. A living proof that the principles behind software design drives code into the same basic patterns of implementation in many code bases around the world.

The project where this code emerged was a windows forms project and the "problem" was to reuse validation with multiple controls and across multiple forms. In my first attempt I tried to reuse the "Validating" event handler. That did not scale well enough across forms so I decided that I needed something else.

My second attempt was to subclass the textbox, but that meant either to create extra events that someone had to subscribe to or make the new textbox depend on any other error informing method like requiring a ErrorProvider to be passed to the constructor . Adding that kind of dependencies was not an option, additionally this approach would also disqualify any third party textboxes already extending the textbox class (a reality in this project) from reusing the validation logic.

For my third attempt I decided to create a class that would "mediate" between the textbox and the ErrorProvider on the form. Using mediation I could defer from using inheritance and did not have to add extra dependencies to my textboxes, thus enforcing SRP and a couple of other three letter abbreviations. It also enabled reuse of the validation for any kind of textbox, not just a certain type.

Enter the star of this post: The TextBoxNotEmptyValidator class.

The design was simple, inject the textbox and the error provider from the outside and let the validator class handle the communication between them (And yes MVC/MVP might have solved the same problem, but that is past the point of this discussion).

The class looked like this:


                        
public class TextBoxNotEmptyValidator { private ErrorProvider errorProvider; private TextBox textBox; public TextBoxNotEmptyValidator(TextBox textBox, ErrorProvider errorProvider) { this.errorProvider = errorProvider; this.textBox = textBox; this.textBox.Validating += TextBoxValidating; } protected void TextBoxValidating(object sender, CancelEventArgs e) { if (string.IsNullOrEmpty(textBox.Text)) Tell("Textbox can't be empty"); else ClearAnyError(); } private void Tell(string message) { errorProvider.SetError(textBox, message); } private void ClearAnyError() { errorProvider.SetError(textBox, string.Empty); } }

                      

A pretty simple implementation; no inheritance needed and fully reusable. The usage was even more simple:


                        
TextBoxNotEmptyValidator validator; . . validator = new TextBoxNotEmptyValidator(textBox1, errorProvider1);

                      

A classic mediator; take two unrelated objects and make them interact with each other using reusable code. This is a standard implementation of the mediator pattern, it could be further enhanced by removing the dependency from concrete classes (TextBox and ErrorProvider) and depend on interfaces instead. For this particular implementation I choose not to, the extra level of indirection would be a pointless exercise since the only scenarios where the validator ever were used just involved textboxes and errorproviders. Later in this project I also combined the mediator with the "composite pattern" to make the reuse even easier and to minimize DRY violations, I will follow up with a separate post on that.  

kick it on DotNetKicks.com
Leave a comment Comments (6)
 
Pattern Focus: MVP, MVC, MVWatever Tuesday, February 20, 2007

This is the third post in my path to save the world with patterns. This time we're going to tackle a manageability and extensibility issue for the project as whole.

The Challenge
I'm sure many of you have been there. You've built a system designed originally for only one customer, but then your manager took the opportunity and sold it to another customer. No harm in that; only the new customer doesn't really like how the information is displayed on the forms. He wants the same functionality with a twist here and there, larger font, an extra textbox and so forth.

This is something that product developers fight with as well every day. To create a generic or flexible enough interface so that all my customers are satisfied.

So what do you do?

Two typical approaches is to lit and hide controls based on configuration in a file or in the database, I've seen this approach a fair amount of times. Another common approach is to branch parts of your solution in your source control system and work with merges back and forth. These two are working solutions but create a lot of overhead in managing the project.

 The most elegant solution I've seen for this problem is one created by XOR a Swedish accounting and business system vendor (they are bought by Visma nowadays). This was back in 2001 and the solution was to build the whole interface based on reusable controls all glued together with VBScript. It was flexible enough and they got great tool support which made it easy to customize. But it took a vast amount of time and resources to build that solution in the first place. What if I don?t want to invest that much time? Am I out of luck?

Fowler et al have described patterns like MVP, MVC, Supervisor Controller, Passive Controller, etc, etc to decouple parts of the UI to make them testable and extensible. Working with a couple of clients that have had this problem, showing them possible ways to decouple the UI and ease the pain of customization and trying to explain the different UI patterns, a small sample implementation  was created.

Instead of doing all these fancy patterns to left and right (even Fowler stated once that no one really understands MVC to its full extent), the sample solution is based on simple inheritance with an extra spice of some reflection code.

The sample solution (I am not going to list loads of code here but just explain the basis of the solution. )
The sample solution is fairly simple. It is based on a single base class. It is called ProductSupervisor in the code since the intention was to implement the supervisor pattern.  I'm not pattern savvy enough to deem it Supervisor or any other pattern, so you will have to judge for yourself. The "controller" in this case is a windows forms object data source placed on the base form. The base form defines all the basic operations all customer forms are to be implementing, list, add, update and delete. It is a bunch of methods with the right signature to be the target of click events. The base form will be the single point of shared code for the different implementations. This could mean that there would be code that isn't invoked from some customized forms but it will be very easy to hook up the functionality if needed later on.

Since all the functionality now is placed in a base form; all the customized form has to do is to place out controls and hook them up accordingly to the base forms events and datasource object.

The sample solution have done this twice, once for CustomerA and once for CustomerB. They are both customers that work with products but preferred to do so differently.
Since there is no physical reference from the application to the two customized forms, the application uses the App.Config to determine which assembly to load and which form to instantiate and does so through reflection.

Roundup
This sample solution is just a proof of concept. There is some work to be done before it actually could make it to production but it's only here to prove a point. Using inheritance, databinding and reflection we can create configurable solutions where only the appearance of the forms has to be different. The main application can stay in the same source control branch and have the customized forms as separate projects. We could even take it one step further and let developers on the customer site use the application as a framework to manage and change the views themselves. All that is really required is to rebuild the dll's and deploy them to production and point them out in a config file.

While not as slick as having your interface being built up by script, it's probably more manageable then branching your solution or trying to hide and show controls on the same form.

References
http://www.martinfowler.com/eaaDev/uiArchs.html

You can download the sample code from the post at the site (yes I know I have to fix it so the blogbost in the feed get's a link as well). It requires the AdventureWorks database or that you create your won three columned product table.

Attached file: UIPatterns.zip
Leave a comment Comments (0)
 
Pattern Focus: Strategy Pattern using delegates Friday, February 09, 2007

Interfaces are the classical way of implementing the strategy pattern, but with .NET we get another similar approach to technically accomplish the same thing. That is by utilizing delegates as part of our parameters list and C# anonymous delegates as our vessel for the strategy.

The first ever discussion I had with Erik Dörnenburg  (http://www.doernenburg.com/) was about delegates, he categorized them as a template interface with one method. While this is not true to a full extent, since they are more complex than that, it is a nice way to look at them in the context of strategy.

Changing the implementation
Instead of creating your own interface and a specific implementation of that interface, you can let the delegate plumbing do it for you. Continuing from the previous example, we could use delegates as the common denominator and act as an interface for the strategies we want. To do this, we just need to create a delegate with the appropriate signature, similar to the signature of the one single method the interface we created in the previous example had.

public delegate bool StrategyDelegate(Consultant consultant); 

Since this delegate will act as our interface, we need to change the parameter list to accept an instance of that delegate instead of the something implementing the IStrategy interface. This will allow us to pass any method with the same signature as the delegate as an in parameter to the method.

Consultant FindFirstSuitable(List consultants, StrategyDelegate strategy)

And finally we need to change the code in the foreach loop slightly:

foreach (Consultant consultant in consultants)  {
                if (strategy.Invoke(consultant))
                    return consultant;
            }

This accomplishes the exact same functionality as we did using interfaces. Although the intent is slightly less clear inside the method for this approach (Invoke don not tell me that much about what it actually checks), I will be able to utilize this function without creating new classes and objects.

Also; with C# 2.0 and the ability to create delegates on the fly, so called anonymous delegates, I will be able to be very precise and clear about the intent when I call this method. For example if I wanted to find a cheap consultant I could write:

Consultant consultant = FindFirstSuitable(consultants,   
                                          delegate(Consultant consultant)
                                          { return consultant.HourRate < 20;
                                          );

When I read this method call; it is quite obvious what my intent is and what the rule passed in actually stipulates. I do not have to look for details in external methods or type definitions.

Looking ahead and into the next version of C# (3.0 or whatever number it will get) this will be even neater with some Lambda expressions from the LINQ package. With Lambda you can express an anonymous delegate like this:

 Consultant consultant = FindFirstSuitable(consultants, consultant => consultant.HourRate <20);

Now that is just straight up beautiful!

Strategy pattern usage in the .Net Framework
This usage of the strategy pattern can be found in many places of the Framework but the most evident is in the List<> class. I have written a sum-up earlier on how that is used so I will not go into details but if you are interested you can read about it here:  https://lowendahl.net/showShout.aspx?id=86

Conclusions
When do we use interfaces and when do we use delegates? There is no clear rule but some guidelines. First of all delegates are much harder to reuse, especially if you use anonymous delegates since they are impossible to reuse, but they are very clear and concise in their intent. Interfaces on the other hand is a bit more complex to implement but will enable you to reuse the strategies across your domain and will let you have more than one method that might be used as part of the decision making. Personally I think that of the two solutions we can use today, interfaces are the more beautiful one (but that will probably change when Lambda is implemented).

The example code for this approach is attached to this post, rss readers need to go to the website to get it.

Attached file: StrategyPattern_Delegates.zip
Leave a comment Comments (4)
 
Pattern Focus: Strategy Pattern Thursday, February 08, 2007

With this blog post I want to start a series. The series will try to shed some light upon different patterns. There are a zillion resources on the web describing patterns, why do it all over again? Well most resources base their explanation for patterns on UML boxes; I would like to explain them in a language which much easier will demonstrate the intent and benefits. For that I've chosen C#.

Initially I wanted to call it "Pattern of The week", but knowing my schedule it would probably be too much to live up to at first. So instead I will call it Pattern Focus for now. The first pattern I would like to start with is an old favorite of mine, the strategy pattern.

Rational
The idea behind the strategy pattern is to simplify the execution and maintenance of methods with complex or wide execution paths.  Using strategies we usually get cleaner APIs and more readable methods and can reuse execution paths across multiple methods instead of just copy and paste it around. It is also easier to extend those methods with new options without making the API really ugly and without touching the method itself.

The Example scenario
The example scenario is very simple but will be able to demonstrate several ways to implement the strategy pattern. The scenario is based on a list of consultants and the idea of trying to find one from the list based on price, skill or both. The method looks like this in its initial form:

static Consultant FindFirstSuitable(List consultants, 
         bool prefereCheap, 
         int maxPrice, 
         bool prefereSkilled, 
        int minLevel) {
            foreach (Consultant consultant in consultants) {
                 if (prefereCheap && consultant.HourRate > maxPrice)
                    continue; 
                if (prefereSkilled && consultant.SkillLevel < minLevel)                
                     continue;  

               return consultant;
           }
            return null;
}

Not the most beautiful method but it does work and will produce the expected result. The problem is though that the intent of this method is not really clear cut. It?s hard to say exactly what is expected to be the right result, or the right way to call it. It could also potentially grow where more criteria?s get added to make the search finer grained. Another point is that now the rules are captured inside this specific method and not useable in any other context.

A clearer Intent
So let?s clear up the intent a bit. In the process we will get a model where we can reuse the rules and expand on the rules without bloating our API's.  To successfully implement the strategy pattern in this scenario we need to identify the point where the execution differs. For our method it is the if statements in the middle of the foreach loop which holds the magic. A bit of the intent is actually clear there, where we have named the Boolean "IsSuitable", this is a great starting point for us to extract the strategy. First we want something to bind all strategies together, one option is to use an abstract base class but I like interfaces better so we will start off by creating an interface:

    public interface IConsultantStrategy {
        bool IsSuitable(Consultant consultant);
    }

This interface quite clearly displays the intent of the strategy, we want to find out if a consultant is suitable for a certain strategy.

Next we create three concrete implementations of the interface, one for each scenario mentioned for this example. All of them get their initial configuration regarding max values in the constructor and all of them implement the IsSuitable method accepting the consultant object to check. I will only show one of them as an example:

public class CheapConsultantStrategy : IConsultantStrategy    {
        private int maxHourRate;        
        public CheapConsultantStrategy(int MaxHourRate) {
            maxHourRate = MaxHourRate;
        }
        public bool IsSuitable(Consultant consultant)        {
            return consultant.HourRate <= maxHourRate;
        }        
}

Now what we have is intent and rules captured in a class ready to be used in our scenario any other similar scenarios. To use this strategy, next we need to change the method declaration and the implementation of the method. The declaration needs to look something like this:

FindFirstSuitable(List consultants, IConsultantStrategy strategy)

The method is now a bit clearer on the intent; it wants a strategy and is communicating that I can choose that strategy by passing an object implementing the IConsultantStrategy interface.

The foreach loop now got a much clearer intent and cleaner code as well, instead of three if statements we only need one:

foreach (Consultant consultant in consultants)   {
                if ( strategy.IsSuitable ( consultant ) )
                    return consultant;
}

To use the method we call it with a strategy object, something like this:

Consultant consultant = FindFirstSuitable(consultants, new CheapConsultantStrategy(20));
Consultant consultant = FindFirstSuitable(consultants, new SkilledConsultantStrategy(2));
Consultant consultant = FindFirstSuitable(consultants, new CheapAndSkilledConsultantStrategy(20, 2));

The above method calls show clear intent which makes it much easier to read and understand what the method will do. I find this to be a very neat way to communicate through the project, not only to yourself but also to other developers that might need to work with your code or API.

Now don not run away and implement strategy all over the place, I know it is a really neat pattern, but it has its place in time and fame.  Considering time and effort you put into creating the strategies, in the form shown here they are really only valuable when you can reuse the strategies in more places of your application or you find yourself writing massive code based on selection statements.

This is the classic implementation of a strategy pattern; with .NET there is a more "light-weight" way to achieve something similar. That will be discussed in a later post (maybe even later today if you are lucky).

The code for this post is attached (for you who get this via RSS readers, you need to go to the website).

Attached file: StrategyPattern.zip
Leave a comment Comments (4)