Comments

I’ve been having a look at coding katas and design patterns over the last couple of weeks. If you are not familiar with either of these concepts then you can read Uncle Bob’s introduction to the Bowling Kata and check out Richard Carr’s great set of articles on design patterns.

My main goals are to:

  • Increase my familiarity with design patterns
  • Understand how design patterns can be best applied in real life situations
  • Develop a repeatable method for memorizing the patterns

A good way to cover off all of these goals will be to develop a set of code kata’s which can be solved by applying a design pattern. Sounds simple? Maybe but lets get started and see how it goes!

The Strategy Pattern

The strategy pattern is defined as

“a design pattern that allows a set of similar algorithms to be defined and encapsulated in their own classes.”

The aim of this pattern is to separate the parts of a system that may change from those which are unlikely to change, allowing for easier maintainability of the system in future. This all sounds good in theory but you may be wondering how and where the pattern can be applied in practice. With this in mind I’ve come up with a fictitious brief that we can solve by utilising the Strategy Pattern.

The brief

A games company is developing a sports event simulator, to be built in iterations starting with simple requirements and building up to increase the complexity. The system design should allow for changes to be made by extending the existing system without changing what is already in place.

  1. The simulator must support marathon and 10 km run events. The only requirement for these events is that the competitors can be displayed in some way (text is fine) and they can compete in the event. All competitors will compete by running.
  2. After running some events they proved to be totally chaotic so each event should now include a marshal. The marshal can also be displayed but does not compete in events.
  3. Since the glorious victory of team GB in the Olympic Triathlon the sport’s popularity has increased. So the games company would now like to also support triathlon events. Again competitors must be displayed and be able to compete, however a triathlon competitor will compete by swimming, cycling and running.

Designing the Solution

The starting point for this kata is available to clone from github here: Strategy Kata Start

Iteration 1

To meet the first requirement we only need a couple of objects as shown below:

Strategy Pattern - Design iteration 1

We can create a couple of events for marathon and 10km runs and add some runners to those events. When the simulation runs the Compete() base method is called for each of the EventAttendees to simulate them taking part in the event. Each of the runners can be displayed by a call to their Render() method.

Iteration 2

We now need to include Marshals as part of the event, so the model is extended as below:

Strategy Pattern - Design iteration 2

However, there is an obvious problem with this design, as noted in the diagram. One option would be for the Marshall to override the Compete method and make it do nothing. However this will store up more trouble for us as there may be other types of event attendee later which do not compete. We would have to ensure that each of these attendees also override that method with the same ‘not compete’ behaviour. There is a better way to design for this issue (there is a clue in the name of this blog post!)

Iteration 3

It is clear that the Compete behaviour may change frequently depending on the attendee, we can leverage the Strategy pattern to extract this behaviour into separate classes as shown below.

Strategy Pattern - Iteration 3

The EventAttendee base class now contains a property of type ICompeteBehaviour. Any implementation of this interface can be assigned to each instance of an EventAttendee. So the Runner class is assigned the Run behaviour and the Marshall class is assigned the DontCompete behaviour.

Iteration 4

We have one more requirement to satisfy, the design needs to be extended to allow Triathlon events to take place. Thanks to our changes in the previous iteration we can add this new requirement without making any changes to the existing classes. Here is the final structure:

Strategy Pattern - Iteration 4

We have extended the EventAttendee class with a new Triathlete class and created a new RunCycleSwim implementation of the ICompeteBehaviour interface. You may be thinking that the same could have been achieved with a method for the behaviour on the Triathlete class, while this is true it limits the flexibility of the design. We can see the advantage of this design by adding Spectators to the simulation. They will also be assigned the DontCompete behaviour, so we have effectively shared this part of the logic without repeating the implementation.

The completed implementation for this kata is available on github here: Strategy Kata End

Comments

My previous blog post, Integrating EPiServer 7 with an existing MVC site, outlined the initial steps to get EPiServer 7 running. However there are a number of additional steps you may need to take before your site is fully integrated.

Convert any Controllers not in Areas

If your site only contains controllers within Areas then you should not need to make any changes. However controllers in the root of the site will not work by default (at least for me). I found it was best to deal with these controllers on a case per case basis as the best course of action depended on the function of the controller. I implemented one of the following changes for each:

  • Move the controller into an area. This option makes sense if the views for the controller do not have any CMS editable content
  • Convert the controller to be CMS managed. Makes sense if the views need to be CMS editable (inherit from PageController<T> where T is a BasePage)
  • Convert the controller to an HttpHandler. In one case the controller did not have any views or models, it was really just a different entrypoint to the site which ran a bit of logic and redirected. In this case there was no point in retaining the controller as an HttpHanlder could do the same job more efficiently

Disable strict language routing

I encountered a further issue after patching my EPiServer.Core and EPiServer.Framework nuget packages to the latest versions. None of the controller actions in the home controller worked any more except for the Index. This was fairly easy to remedy by disabling the strict language routing, via the episerver/sites/site/strictLanguageRouting config setting.

Deployment Issues

While its all well and good having the site running on your machine, eventually it will need to be deployed somewhere. We handle configuration changes with file transforms and I was pleased to note that the config changes required for episerver deployments are now minimised. Here is a summary list of all the settings we changed per environment:

  • connectionStrings
  • episerver/sites/site/siteSettings/siteUrl
  • episerver.framework/siteHostMapping/siteHosts
  • episerver.framework/appData/basePath
  • episerver.framework/licensing/licenseFilePath
  • episerver.search/namedIndexingServices/services/baseUri

Note, you may need to transform further settings for a load balanced site.

EPiServer UI not deployed

Previously with EPiServer v6 all that was needed to run the CMS interface itself was to install the application on the web server. However the EPiServer 7 UI architecture also has a number of dependencies in the {VPP}\modules folder. So ensure that these files are also present in your deployed environment, otherwise you will probably encounter the following error:

DirectoryNotFoundException: Could not find a part of the path '{Your site path} \Website\ClientResources\ClientResources\packages.config'
Search service configuration

We have the search service configured on a local host name as the indexing service does not like to communicate over a public host name. However this caused a further issue with the service reporting that multiple hosts names could not be run for the service. Fortunately this could be remedied easily by setting the system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled setting to true.

Those were all the steps we needed to take to deploy the site successfully. I’d be interested to hear your experiences if you found any other settings that need to be changed. Feel free to reply in the comments below or contact me directly on twitter @michael_hook.

Comments

custom_integrationThis post assumes you have EPiServer 7 installed on your machine. If you don’t have it then it is available from EPiServer world (once you have created an account).

There are 2 main options for creating a new EPiServer 7 MVC stylee site:

For integrating with an existing site I’d recommend using option 1, as there are far less files to integrate. However it is well worth looking at the templates package as well as this demonstrates how models and views can be implemented with EPiServer 7.

After creating the new Visual Studio project I remembered that EPiServer have a NuGet feed, and they do have the version 7 assemblies on NuGet. However the version numbers are slightly different to those used in the visual studio project, so make sure you specify the version numbers to NuGet when you install the packages (they are listed below). Here are the steps I followed in detail:

  1. Created a new Visual studio project using the EPiServer Web Site (MVC) template
  2. Followed the EPiServer tutorial (link) to add a home page and set it to the ‘start page’
  3. Upgraded my existing site to MVC 4 by installing the Microsoft ASP.NET MVC 4 nuget package (obviously not required if your existing site is already on MVC version 4.
  4. Copy across the connectionStrings.config, episerver.config, EPiServerFramework.config, EPiServerLog.Config and FileSummary.config files
  5. Update the siteUrl in episserver.config.
  6. Copy the AppData, IndexingService, modules and modules bin folders.
  7. Merge the web.config files - ensure the episerver.search baseUri is updated to point at your site address.
  8. Installed EPiServer 7 from Nuget feeds using these commands to get the correct versions:
    • Install-Package EPiServer.Framework -Version 7.0.859.1
    • Install-Package EPiServer.CMS.Core -Version 7.0.586.1
  9. Removed assembly references to Razor and System.WebPages.Razor (as was clashing with EPiServer versions)
  10. Update Controllers to inherit from PageController<T> where T is a PageData class.
  11. Update Global.asax to inherit from EPiServer.Global

IoC containers clashing!

OK, this is the tricky bit it gets quite involved but please stay with me!

When I tried to run the site it now returned a ‘No parameterless construct or defined for this object.’ message. Which in plainer English means the application can’t create the Controller classes. This is because the site I am integrating with currently uses the Castle Windsor IoC container, however EPiServer uses the StructureMap IoC container internally. We definitely don’t want two IoC containers and I can’t see any evidence of the EPiServer container being swappable. So the only option here is to convert the current Windsor implementation to a StructureMap implementation. More information on Structure map can be found on the excellent StructureMap documentation site, however I think it is worth including an overview in this post as, whilst this isn’t always going to be necessary for your site, I expect it will be a common problem.

Add StructureMap version 2.6.1.0

This is available from NuGet (as this is the version used in the EPiServer 7 MVC templates package). The command to install is: Install-Package StructureMap -Version 2.6.1.0

Register your services with StructureMap

  • Copy the StructureMapDependencyResolver and DependencyResolverInitialization classes from the EPiServer MVC templates project.
  • Convert service registration calls to register services with StructureMap instead of Windsor. This is carried out in the ConfigureContainer method of the DependencyResolverInitialization class.

For example here is a Windsor interface registration and its equivalent StructureMap registration:

//Windsor registration - Here container is an implementation of IWindsorContainer
var myConfig = WebConfigurationManager.GetSection("myConfig") as MyConfig;
container.Register(Component.For(typeof(IMyConfig)).Instance(myConfig));
//StructureMap registration - Here container is of type ConfigurationExpression
var myConfig = WebConfigurationManager.GetSection("myConfig") as MyConfig;
container.For<IMyConfig>().Use(myConfig);

An example of a class registration with a singleton lifestyle:

//Windsor registration
container.Register(Component.For(typeof(Cache)).Instance(HttpContext.Current.Cache).LifestyleSingleton());
//StructureMap registration
container.For(typeof(Cache)).Singleton().Use(HttpContext.Current.Cache);
  • Convert IWindsorInstaller implementations to Registry subclasses.

Debugging your StructureMap registrations

You can debug structure map by adding this line:

_container.AssertConfigurationIsValid();

Initially EPiServer was reporting many registration failures but you can delay the call until the InitComplete event is called in the DependencyResolverInitialization class. Then most of the EPiServer registrations have completed and it is easier to see if there are any issues with your own services.

Manually retrieving a service

Generally my services are injected into constructors automatically, however I had a couple of calls to retrieve services manually from the IoC container. For example, to retrieve an implementation of an interface called IMyService:

_var myService = DependencyResolver.Current.GetService<IMyService>();

Last steps

Hopefully your site will be running now, there is some additional configuration work you may want to do for EPiServer 7 VPP folders. But if you’ve made it this far you will probably need a break!

Updated on 9th April 2013

Updated the list of config files which must be copied to include EPiServerLog.config and FileSummary.config

Comments

Annie the ContortionistOne of the great aspects of the Git source control system is its flexibility. Almost any sticky situation you may encounter as a developer working with source control can be solved with Git.

Take this scenario, you’re halfway through writing a class for a new feature when you get a call.. the client has found a show stopping bug in the application and it needs to be fixed right away. To be able to fix the bug you will need to switch onto the live code branch but you can’t go switching branches with a load of uncommitted changes. Now you don’t want to commit your code as its half done and won’t even compile right now, but you don’t want to lose the changes either… git stash to the rescue!

When you issue the git stash command all your changes will be committed to a stack. Leaving you with no changes on your current working branch and free to branch where ever you want. So now you can switch to the live branch and do your bug fixing work. Once that is done you can simply move back to the feature branch and apply the stashed changes. Hey presto, you are back where you started with your uncommitted half complete work!

If you really get into lots of parallel work you can stash multiple times, just be sure to remember that it is a stack and your last changes you have stashed will come back off stack first.

Comments

A landmark decision was made last week by Microsoft’s ASP.NET web development team. They announced that three key technologies used to develop web applications, ASP.NET MVC, Web API and Razor would be made fully Open Source1. This is a big step for a company built on the sales of Closed Source software. I’m going to have a look at what I think this decision means for the consumers, who use software built with these technologies, and the stakeholders who commission the software.

Open Sesame

For those those not involved directly in software development, the moniker ‘Open Source’ may conjure up images of magicians pulling rabbits out of a hat2. However the reality could be viewed as the opposite of magic as Open source demystifies the software development process. In the traditional ‘Closed Source’ licencing model, software is made by a company behind closed doors and the code is encrypted before release to the public. The traditional thinking is that this protects the company by preventing third parties from stealing their intellectual property. This is a subject of some debate , which I won’t go into here. However it is clear that many businesses are currently successful without relying on restrictive software patents.

In an Open Source licencing model, the full unencrypted source code will be published at the same time as the software itself (indeed often before-hand in the case of preview and beta releases). Also, as in the case of this announcement, public contributions may be accepted to modify the original source code. Naturally the acceptance process is completely at the discretion of software company, so unhelpful or damaging contributions will not be accepted.

A good example of the Open Source model working commercially is the Android operating system released by Google. A massive range of mobile devices run Android and it is not only the key competitor to Apple’s iOS (iPhones & iPad operating system but has helped ensure that most devices using Microsoft’s Windows Mobile operating system are sitting on the scrap heap. I for one am glad that there is healthy competition to the world of Apple and its clone army of i-device accolytes.

Software that Just Works

From a consumer or stakeholder viewpoint the natural desire is to want software that ‘just works’ and to reach that goal we just need to fix all the bugs in the software. Unfortunately the belief that all software bugs can be fixed is generally infeasible given time and budget restraints, due to the nature of programming the two go hand in hand. In each piece of code there are many paths that can be travelled, much like a maze in a country mansion garden. If you ask 10 different people to walk the maze the chances are each one will set off in a different direction. Most of them will hit a dead end before finding their way through and a nasty bug could be hiding at each of these dead ends!

However Open Source software helps minimize the number bugs by accepting contributions to fix any that are found by the development community. In this way the software benefits from the knowledge of a much wider group of people than could be acheived if it was developed and maintained soley by a single company. Most software developers are driven by that itch to ‘make stuff work’ and are only too happy to contribute to a project which helps make this happen. The end result is a product that is more reliable for the consumers and stakeholders and has the appearance of ‘just working’.

Security concerns

Typically the biggest obstruction to making software Open Source is the perceived risk to security. If anybody can view exactly how the software is operating then it is much easier for hackers to cause the software to break, exploit a vulnerability to propogate a virus or carry out other nefarious acts. The indications by Phil Haack, a former member of the MVC team, are that this decision by Mircosoft is no exception. So a great deal of credit should go to those involved at Microsoft for making change happen in their organization.

Regarding the perceived risks to security, Open Source can actually reduce the risk for similar reasons to the improvement in relibility. Any security vulnerabilities will quickly be picked up by the community and fixed. The Open Source culture of continual improvement in the software makes for a much more secure product.

Take the example of web browsers, a couple of years ago Microsoft’s Internet Explorer browser had massive market share. However over time so many security vulnerabilities were exploited in the browser that the US government themselves warned against using the software! Along came Mozilla’s Firefox browser to save the day, with much improved security. Naturally Firefox has always been developed under an Open Source licence as explained in the Mozilla manifesto.

Future developments

The likelyhood is that this announcement will not trigger a deluge of community updates and fixes to the frameworks in question. I anticipate that a minority of change submissions will make it back into the frameworks themselves. However it does demonstrate an important change in mindset from Microsoft and may well signal the beginnings of a new approach for the organisation. It is clear that in the fast moving world of software and digital media you need to adapt to survive and it is encouraging that even massive organisations such as Microsoft are able to do this.

Footnote

1While the MVC framework has been open source since its original release, this announcement widens the license model to the Web API and Razor frameworks and also marks the first time that Microsoft will accept public contributions to the open source frameworks. If you are unfamiliar with these technologies then further information is available on the Microsoft blah blah (LINK).

2Or maybe thats just my fertile imagination!

Copyright © 2016 - Hook Technologies Ltd - Powered by Octopress