How do you make the selected tab standout in an ASP.NET Mvc Project? This is a fairly common task for every sort of web project, we usually do this to help the user keep track of where they are. But unfortunately this functionality is not built-in and you have to do some manual labor to make it all work. Here is one of the technique that you can use to implement this, which also works with AREAs. Here is the end product:
So basically Electronics is an area which consists of two controllers in my case. The selected menu and any sub-menu will be marked as red.
First create a base Menu class that knows how to display itself using the RequestMatch method to determine whether to mark itself as selected based on current request. It then forwards the call to an extension method. This base menu class is sufficient if you only have to deal with one level menus, meaning no sub-menus.
Since the SubMenu is the last node, it can use the base functionality here.
The MainMenu however needs to override the DisplayMenu method because it also has to take into account whether one of its submenu’s is selected or not. If any of its sub-menu is selected than the main-menu must also stay selected. This is the only tricky logic that you have to take into account. Now to make everything work you need to create an HtmlHelper extension method like so:
The Menu extension method is pretty simple, it grabs the “action”, “controller” and ”area” values from routeData and this is what we’ll use to determine which menu to mark as selected using the DisplayMenu method.
If you haven’t already noticed I can also turn individual menus on/off based on whether the current user is authorized or any other constraints you can think off. That logic is placed in the MenuActionLink extension method and you can use the given htmlHelper to expose any values you want for e.g., (htmlHelper.ViewContext.HttpContext); In my case it simply checks for that property. Now change your Layout views to use the Menu extension method:
When creating Main-menu you also have to register any sub-menus that it will have, similar to what I’ve done for the Electronics Main menu. Also notice that I’ve set authorizedOnly parameter to True for the About Main menu, which will turn it off in my implementation.
Singletons are one of the most used (abused) design patterns that people like to use. There will be only one instance of this class for the entire application, what a performance boost. However, most of the times you can just use a regular class instead of a Singleton to accomplish the same task. There are several things that I don’t like about the classic Singleton pattern
- It is really hard to test.
- It violates Separation of Concerns by internally creating instances of itself – a class should not concern itself with lifetime management.
- Lot of work to make it a non-singleton later on
First let’s look at an example where making a class a Singleton improves performance:
– Non-Singleton: Here I have a non-singleton class (MyCustomNonSingleton) which initializes a new instance of ExpensiveResource in order to get its data (whatever that might be – here it’s just a string to make it simple). ExpensiveResource class simulates delay by pausing for 2 seconds each time it is initialized. Then at the end I get three resources from MyCustomNonSingleton classes and simply print them on the console.
- Costs (6 seconds) – each time MyCustomNonSingelton class is initialized it also initializes ExpensiveResource class, which takes 2 seconds each
– Singleton: Above is my Singleton implementation using .NET 4.0 System.Lazy<T> type, which makes it simple and obvious that the class will be initialized lazily (msdn: http://msdn.microsoft.com/en-us/library/dd642331.aspx).
- Costs (2 seconds) – MyCustomSingleton class is initialized the first time when the program tries to access the “Instance” property. So we only take that initial 2 second hit of creating ExpensiveResources class, after that any call to MyCustomSingleton.Instance from anywhere in your program, will simply be handed the same instance of that class (all initialized and ready for you to use).
- However as I mentioned above that even though this design is effective it does not support UnitTest by default.
– IOC Singleton: This is my preferred method of creating Singletons. You can basically have your cake and eat it too! In this example I am using Ninject but you can use any popular IOC container you prefer and they all support the concept of SingletonScope. Here during the bind process you simply tell Ninject to create this as a singleton – and you are done! Now anywhere in your application where you ask ninject to get you an instance of some class it will create a new instance if it is the very first time, else it will hand you the same instance that it already created.
- Costs (2 seconds) – Here in my example the first call to kernel.Get<IMySingleton>(), ninject goes through the initialization process for MyCustomNonSingleton class (2 seconds), during the subsequent calls to kernel.Get<IMySingleton>(); it simply returns the same instance.
- Extremely easy to implement
- Even easier to make it a non-singleton later on if design changes, simply remove (.InSingletonScope())
- Allows separation of concerns by taking out the lifetime management responsibility from the class
- Last but not least, it is now UnitTest friendly. You can use any Mocking framework to mock an implementation for IMySingleton interface during testing.
Knowledge of software design patterns is a useful tool to have in your tool belt, and one that will come in handy from time to time. Today I was thinking of ways of applying caching to existing repositories and the one pattern that stood out was the Decorator pattern. The concept is fairly simple – decorate repositories with a caching implementation. Most caching follows similar path, let’s say we have a method called “GetProduct(int productId)” here are the steps that it will usually follow:
– See if the product is in cache; if yes then return
– If no; then get it from the database – add it to the cache and return the value
Here is my sample application that decorates EmployeeRepository with a caching implementation. This does look little bit different than a pure decorator pattern and that’s because I had to take into account how Ninject binding works.
The IEmployeeCacheDecorator interface simply extends IEmployeeRepository, the reason for that little bit of indirection is so that I can tell ninject to basically give me two implementations of IEmployeeRepository like so
because I need and instance of EmployeeRepository to use in my decorator. Now as you can see, anytime someone calls FindById – I first look in my cache and if it’s not there then I forward the call to my repository, which looks in my database. The reason that EmployeeCacheDecorator class extends EmployeeRepository rather then getting injected through the constructor is because now I can pick and choose only the methods that I want to apply caching to and leave the other ones untouched. Here is the class that uses this decorated cache class:
I think this is a good way of applying caching, logging or any other things that you want to do before or after hitting your database. It leaves your existing system in place and does not pollute your pure data access code (repositories) with other concerns. In this case both classes have their own responsibilities, when it’s not in the cache the decorator class delegates the task to the repository and let it deal with the database. Do I hear Single Responsibility Principal—