When working with visual studio you have the ability to use regions in your code to easily expand or collaps serveral lines of code. This can be very powerful but can lead to less testable (and seperated) code if not used properly.
Separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern.
Literally, this means visual studio sections can help you in seperating your code file in sections, each responsible for their own concern. But this is incorrect, taking in mind most of the coding principles.
Taking Seperation of concers in mind while setting up your project structure results in the creation of different projects, classes and functions, designed in such a way that each of these objects have a logic meaning compared to it’s parent.
I.e. A Domain project should contain only your domain objects with only properties/methods for this object. Data Access objects should be stored in a different project, which can make use of the objects from the domain project.
Above can not be achieved with visual studio sections, since you devide your class in “visual” sections. Which is great, when not used to seperate “logic” sections of your code.
Lets take the following example:
private static void CreateOrderForUser(int userId)
{
#region :: Get data from a datasource ::
// Get the info for the current user
// Get the current user from an Entity Framework context
var context = new MyContext();
var currentUser = context.Users.FirstOrDefault(u => u.Id == userId);
#endregion
if (currentUser == null)
throw new ArgumentException(string.Format("No user with Id '{0}' found.", userId));
#region :: Manupulate data based on input ::
// The user has created a new order, create a new order here
var newOrder = new Order { UserId = currentUser.Id };
#endregion
#region :: Send email to user ::
// Sent mail to [currentUser.EmailAddress]
// Mailing code copied from: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
var client = new SmtpClient("[SMTP SERVER]");
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
var from = new MailAddress("jane@contoso.com", "Jane " + (char)0xD8 + " Clayton", System.Text.Encoding.UTF8);
// Set destinations for the e-mail message.
var to = new MailAddress("ben@contoso.com");
// Specify the message content.
using (var message = new MailMessage(from, to))
{
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
var someArrows = new string(new[] { '\u2190', '\u2191', '\u2192', '\u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
client.Send(message);
}
// set the "IsMailSent" property to 'true'
newOrder.IsMailSent = true;
#endregion
#region :: Update database with input data after email was sent ::
// Save the new order to the database
context.Orders.Add(newOrder);
#endregion
}
When the regions are collapsed, this code looks very clean:

But actually this method is doing different things, which should be seperated.
Refactoring this method in seperate objects will encourage better testability and maintainability of your code.
Also will refactoring remove the use of regions in this method, since they are replaced with fewer method calls.
private static void CreateOrderForUser_Refactored(int userId)
{
var userRepository = new UserRepository();
var orderService = new OrderService();
// Get the info for the current user using a repository, here we can seperate all data acces logic.
var currentUser = userRepository.GetById(userId);
if (currentUser == null)
throw new ArgumentException(string.Format("No user with Id '{0}' found.", userId));
// Create new order, we do not care what is going to happen behind the screens.
// We just want to "create a new order", everything that is related to this action
// has to be executed without the caller needs to take any extra action.
// Since we need more than just "database actions" we create an extra service layer, which will be using a repository
// to take care of any neccesary database actions.
orderService.NewOrder(currentUser); // Pass extra order information here
}
This code looks pretty clean aswell, without using any regions:

Using sections is not a crime, just make sure you use them wisely!
Source code available here
I’ve been digging into Test Driven Development for a while now and it’s power inside corporate applications.
While working on a project running Entity Framework 5 I came to a point where I wanted the best way to test my Data Access Layer (repository, dao, …).
On my blog post: Mocking Entity Framework using ObjectContext and database first I explain how to use any Mocking framework to fake your EF context.
This works pretty smooth but it can be dangerous.
When searching around the internet you find many people explaining how to mock EF context, but there are only a few (I only found one tbh Ladislav Mrnka) explaining why you SHOULD NOT mock your context. Ladislav Mrnka posted a great reply on stackoverflow about mocking EF context: http://stackoverflow.com/questions/6766478/unit-testing-dbcontext.
I am not saying you should not fake your EF context but it is very important to understand it is not 100% bulletproof, meaning there will still be possible scenario’s where your unit test runs succesfully but you will get runtime exceptions.
Lets take Ladislav’s example and show you what might go wrong:
The following method inside the UserRepository contains a call to System.IO.File.Exists()
public IList<User> GetWhereImageNotExists()
{
return _context.Users.Where(u => !File.Exists(u.PictureUrl)).ToList();
}
This repository method can be tested using a fake EF context :
[TestMethod]
public void FakeContext_GetWhereImageNotExists()
{
// Create Fake user Data, this will replace our Database entries.
var userList = new List<User>
{
new User() { Id= 1, Name = "Frederik", PictureUrl = "test" },
new User() { Id=2, Name = "Admin", PictureUrl = "test2" }
};
// Create a new instance of the MoqDbSet class, this will be our mocked replacement for the IDbSet Users property
IDbSet<User> moqUserObjectSet = new MoqDbSet<User>(userList);
// Create mock for IUserContext and bind the Users property to our mocked "MoqDbSet" implementation
var mockContext = new Mock<IUserContext>();
mockContext.Setup(m => m.Users).Returns(moqUserObjectSet);
// Tests
var shopRepository = new UserRepository(mockContext.Object);
Assert.AreEqual(shopRepository.GetWhereImageNotExists().Count, 2);
}
The test will result in succesfully when using a fake context.
[TestMethod]
public void DbContext_GetWhereImageNotExists()
{
var ctx = new UserContext();
// Tests
var shopRepository = new UserRepository(ctx);
Assert.AreEqual(shopRepository.GetWhereImageNotExists().Count, 2);
}
This test will fail, while the same code tested with a fake context was successful.
Test method Moq.EntityFramework.Dangerous.Tests.EFContexTests.DbContext_GetWhereImageNotExists threw exception: System.NotSupportedException: LINQ to Entities does not recognize the method 'Boolean Exists(System.String)' method, and this method cannot be translated into a store expression.
This exception is thrown because of the difference between Linq to Objects en Linq to Entities. When using a fake EF context our linq queries will be executed against Objects, while they are executed against Entities when using the real EF context.
As you can read in the exception, Linq to Entities does not support the System.IO.File.Exists method. Ofcourse EF can not translate this method to a SQL variant (since this is what EF does behind the screens).
Summary
Mocking EF context works pretty good but it is safer to use Integration Testing when testing anything that is dependent on an EF Context.
Source code available @ github.
I have been working with Entity Framework for awhile now and start to like it more and more.
Until now we have always run unit tests on the Entity Framework model itself, no mocking was used yet.
But ofcourse, for unit testing, we all know it can be pretty powerful to use any kind of mocking framework (such as Moq, the one I will be using).
Mocking is made possible by using interfaces in your application, but as you might have noticed… Our generated ObjectContext will not inherit any interface (depending on your T4 templates ofcourse):
public partial class ShopEntities : ObjectContext
{
// Some Code left out
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Order> Orders
{
get
{
if ((_Orders == null))
{
_Orders = base.CreateObjectSet<Order>("Orders");
}
return _Orders;
}
}
private ObjectSet<Order> _Orders;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<Product> Products
{
get
{
if ((_Products == null))
{
_Products = base.CreateObjectSet<Product>("Products");
}
return _Products;
}
}
private ObjectSet<Product> _Products;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<User> Users
{
get
{
if ((_Users == null))
{
_Users = base.CreateObjectSet<User>("Users");
}
return _Users;
}
}
private ObjectSet<User> _Users;
}
So while writing unit tests we can not mock our ShopEntities class and therefor are dependent on the database entries. This means that if the amount of users in the database is not equal to 2, the following unit test will fail.
[TestMethod()]
public void GetUsersTest()
{
ShopEntities context = new ShopEntities();
ShopRepository shopRepositories = new ShopRepository(context);
var users = shopRepositories.GetUsers();
Assert.AreEqual(users.Count, 2);
}
To fix this, you can make use of an interface from which our ShopEntities will inherit. This interface will declare the signatures of the “ObjetSet” (IObjectSet eventually) properties, these are the ones we call to get specific data from our datasource using linq to entities and therefor the ones we, eventually, want to mock.
Ofcourse you can create this interface using T4 templates, but I will focus on the interface here instead of generating it through T4 templates. (I will try to create a blog post about T4 templating pretty soon).
What we want is an interface like this:
public interface IObjectContext
{
IObjectSet<Order> Orders { get; }
IObjectSet<Product> Products { get; }
IObjectSet<User> Users { get; }
}
and an ObjectContext like this:
public partial class ShopEntities : ObjectContext, IObjectContext
{
// Some Code left out
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public IObjectSet<Order> Orders
{
get
{
if ((_Orders == null))
{
_Orders = base.CreateObjectSet<Order>("Orders");
}
return _Orders;
}
}
private IObjectSet<Order> _Orders;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public IObjectSet<Product> Products
{
get
{
if ((_Products == null))
{
_Products = base.CreateObjectSet<Product>("Products");
}
return _Products;
}
}
private IObjectSet<Product> _Products;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public IObjectSet<User> Users
{
get
{
if ((_Users == null))
{
_Users = base.CreateObjectSet<User>("Users");
}
return _Users;
}
}
private IObjectSet<User> _Users;
}
As you can see I have used IObjectSet instead of ObjectSet, this is because at the end we want to create our own “ObjectSet” implementing the IObjectSet interface.
Because ObjectSet can not be used to store values in memory, we will be faking our own IObjectSet upon testing.
Since we are using IObjectSet inside the IObjectContext interface and the ShopEntities ObjectContext, we will be able to Mock our own IObjectSet implementation.
Now our entity framework is set up to be mockable!
Create the Unit Tests
As I said, we make use of a fake IObjectSet implementation while mocking: MoqObjectSet
public class MoqObjectSet<T> : IObjectSet<T> where T : class
{
public MoqObjectSet()
: this(Enumerable.Empty<T>())
{
}
public MoqObjectSet(IEnumerable<T> entities)
{
_set = new HashSet<T>();
foreach (var entity in entities)
{
_set.Add(entity);
}
_queryableSet = _set.AsQueryable();
}
public void AddObject(T entity)
{
_set.Add(entity);
}
public void Attach(T entity)
{
_set.Add(entity);
}
public void DeleteObject(T entity)
{
_set.Remove(entity);
}
public void Detach(T entity)
{
_set.Remove(entity);
}
public Type ElementType
{
get { return _queryableSet.ElementType; }
}
public Expression Expression
{
get { return _queryableSet.Expression; }
}
public IQueryProvider Provider
{
get { return _queryableSet.Provider; }
}
public IEnumerator<T> GetEnumerator()
{
return _set.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
readonly HashSet<T> _set;
readonly IQueryable<T> _queryableSet;
}
Now we are able to mock our ObjectContext while writing unit tests and passing the mocked Object Context to our Repository
public class ShopRepository : IShopRepository
{
private readonly IObjectContext _context;
public ShopRepository()
{
_context = new ShopEntities();
}
public ShopRepository(IObjectContext context)
{
_context = context;
}
public IList<User> GetUsers()
{
return _context.Users.ToList();
}
public User GetUserById(int id)
{
return _context.Users.SingleOrDefault(u => u.id == id);
}
}
[TestMethod()]
public void MoqGetUsersTest()
{
// Create Fake user Data, this will replace our Database entries.
var userList = new List<User>
{
new User() { id=1, username = "Frederik", password = "test" },
new User() { id=2, username = "Admin", password = "test2" }
};
// Create a new instance of the MoqObjectSet class, this will be our mocked replacement for the IObjectSet Users property
IObjectSet<User> moqUserObjectSet = new MoqObjectSet<User>(userList);
// Create mock for IObjectContextand bind the Users property to our mocked "MoqObjectSet" implementation
var mockContext = new Mock<IObjectContext>();
mockContext.Setup(m => m.Users).Returns(moqUserObjectSet);
// Tests
var shopRepository = new ShopRepository(mockContext.Object);
Assert.AreEqual(shopRepository.GetUsers().Count, 2);
Assert.AreEqual(shopRepository.GetUserById(2).username, "Admin");
}
As you can see, in the above unit test we create a MoqObjectSet based on our List of User collection.
This IObjectSet implementation is then bound to the IObjectContext.Users property, meaning that our repository will now be querying this set of Users instead of my Sql database.
That is why we can now compare the result to the expected result based on the List of User collection: 2 entries and the user with id 2 has the “Admin” username.
Now, editing or adding database entries will not affect this unit test in any way!
Using Include
If you come to a point where you turn of lazy loading and you want to control the Included navigation properties, you will find out this is not working.
The reason for this is we are working with IObjectSet implementations instead of ObjectSet’s. IObjectSet does not support the use of Include, which is why we will provide our own Include method by creating an extension method:
public static class Extensions
{
public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
var objectQuery = source as ObjectQuery<TSource>;
if (objectQuery != null)
{
return objectQuery.Include(path);
}
return source;
}
}
Now you can use the Include method as how you would use it with ObjectSet’s
public class ShopRepository : IShopRepository
{
private readonly IObjectContext _context;
public ShopRepository()
{
_context = new ShopEntities();
}
public ShopRepository(IObjectContext context)
{
_context = context;
}
public IList<User> GetUsers()
{
return _context.Users.Include("Orders").ToList();
}
public User GetUserById(int id)
{
return _context.Users.Include("Orders").SingleOrDefault(u => u.id == id);
}
}
Source code and Database can be found at github.
You might come to a point where you would like your code to be executable by a server admin with a single mouseclick. Several options are available to achieve this, one of this is by creating a PowerShell script.
When creating a PowerShell script (.ps1 file) you can use built in PowerShell CmdLets, which allow you to do alot of things. But it might occur that you have the need to create a custom CmdLet to allow you to execute custom code with a single powershell command which is reusable on the server.
Creating a custom CmdLet is pretty straightforward, start by creating a project (can be classlibrary or inside your sharepoint solution) to contain your CmdLet class. This project’s assembly has to be deployed to the GAC.
Start by adding a reference to System.Management.Automation.dll, if you are having problems locating this file check the GAC folder.
Add a class file named MyCmdLet.cs to the project and make sure the code is looking like the example:
// Using this attribute, the CmdLet can be called using the "Set-MyCustomCommand" command in PowerShell
[Cmdlet(VerbsCommon.Set, "MyCustomCommand")]
public class MyCmdLet : Cmdlet
{
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
public string Parameter1
{
get;
set;
}
[Parameter(Position = 1, Mandatory = false)]
[ValidateNotNullOrEmpty]
public string Parameter2
{
get;
set;
}
protected override void BeginProcessing()
{
base.BeginProcessing();
// Do your thing
}
protected override void ProcessRecord()
{
WriteObject("ProcessRecord started");
try
{
// Your code to be executed goes here.
WriteObject(string.Format("Parameter1 has a value of '{0}'.", Parameter1));
}
catch (Exception e)
{
WriteObject(new ErrorRecord(e, "UpdateListFeaturesCommandlet", ErrorCategory.NotSpecified, null));
}
WriteObject("ProcessRecord ended");
}
protected override void EndProcessing()
{
base.EndProcessing();
// Do your thing
}
}
As you can see I have added an attribute to the “MyCmdLet” class
// Using this attribute, the CmdLet can be called using the "Set-MyCustomCommand" command in PowerShell
[Cmdlet(VerbsCommon.Set, "MyCustomCommand")]
public class MyCmdLet : Cmdlet
This attribute specifies which command will be used to execute your custom code. Since I’ve set the “Set” prefix and the “MyCustomCommand” suffix, our command will become available in PowerShell as Set-MyCustomCommand. You can change this to anything you like. (make sure it makes sense).
Apart form this class attributes, there are also some attributes used on the properties. These are just to specify the order in which they are supposed to be inserted and whether they are required or not.
[Parameter(Position = 0, Mandatory = true)]
[ValidateNotNullOrEmpty]
public string Parameter1
{
get;
set;
}
[Parameter(Position = 1, Mandatory = false)]
[ValidateNotNullOrEmpty]
public string Parameter2
{
get;
set;
}
All that is left to implement your behaviour is to override the desired method(s):
- BeginProcessing
- ProcessRecord
- EndProcessing
protected override void BeginProcessing()
{
base.BeginProcessing();
// Do your thing
}
protected override void ProcessRecord()
{
WriteObject("ProcessRecord started");
try
{
// Your code to be executed goes here.
WriteObject(string.Format("Parameter1 has a value of '{0}'.", Parameter1));
}
catch (Exception e)
{
WriteObject(new ErrorRecord(e, "UpdateListFeaturesCommandlet", ErrorCategory.NotSpecified, null));
}
WriteObject("ProcessRecord ended");
}
protected override void EndProcessing()
{
base.EndProcessing();
// Do your thing
}
It is not mandatory to override all of these method’s. For small Cmdlets, I only override the ProcessRecord method.
You can use the properties like in any other c# class, so implement your logic inside the override method(s) like you would do in any other project.
Install the PowerShell Cmdlet
A custom PowerShell Cmdlet can be installed using different approaches. Since I mainly focus on SharePoint I have decided to explain the installation using a WSP file. This installation approach is not so widely documented.
PowerShell commando’s can be registered by adding an XML file (or modifying an existing one but that’s not realy the way to go) in the following folder in the SharePoint folder:
\14\CONFIG\POWERSHELL\Registration
Since this is a folder, located in the 14 hive, start by adding a mapped SharePoint folder to your project (pointing to the above location).
Next, add an xml file (the file’s name does not matter) to the mapped folder and change the content like so:
<?xml version="1.0" encoding="utf-8" ?>
<ps:Config xmlns:ps="urn:Microsoft.SharePoint.PowerShell" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:Microsoft.SharePoint.PowerShell SPCmdletSchema.xsd">
<ps:Assembly Name="$SharePoint.Project.AssemblyFullName$">
<ps:Cmdlet>
<ps:VerbName>Set-MyCustomCommand</ps:VerbName>
<ps:ClassName>[NameSpace.ClassName]</ps:ClassName>
<ps:HelpFile>[AssemblyName].dll-help.xml</ps:HelpFile>
</ps:Cmdlet>
</ps:Assembly>
</ps:Config>
Important to note is that in the above snippet, the HelpFile does not have to exist. It may exist but it is not required.
If you now deploy your wsp, the above xml file will be provisioned to the \14\CONFIG\POWERSHELL\Registration folder and your custom PS Cmdlet should be available in the SharePoint Management Shell (or include the Microsoft.SharePoint.Powershell snapin using: Add-PSSnapin “Microsoft.SharePoint.PowerShell” in the Windows Powershell window)

As most of you know, SharePoint has a versioning option which can be enabled and configured on a library base:

Most of the people will look at this boxes as a “major minor versioning”, meaning they will enter e.g. 5 in both boxes. By entering these values, alot of users will think they have just told SharePoint to only keep the last 5 major versions and the last 5 minor (unpublished) versions for each of these 5 major version. This way, your library will never be filled with 100′s of versions.
If you agree with the statement above, sadly, I have to tell you that you are completely wrong and misunderstanding the versioning system which SharePoint is using.
There is no “out of the box” way to limit the amount of minor versions for a major version.
So, why is this second box there?
This box is there for the reason it is designed to be there. Take a closer look at the textbox’ description:

As you can see, it is not ment to be used to limit the minor versions. It is used to only keep all minor versions for the specified amount of major versions (Keep drafts for the following number of major versions).
This way of using versioning has 2 consequences:
- You can not limit the amount of minor versions, meaning that if your users never use the publish button, you can still have 200000+ versions.
- The value of the second box can never be greater than the first one. This is because in the first one you are specifying how many major versions to keep. While in the second box you are specifying for how many major versions you want to keep all the minor versions.
I have seen alot of SharePoint users (or even specialists) misunderstanding this versioning system. So did I btw, until I managed to read this textbox’ description correct.
I have created a solution to clean your SharePoint library by executing some code to only keep x major versions and only keep y minor versions for each major versions (since this is what some customers may require). I’ll try to package this as a reusable component and upload it as soon as possible.
Since I started doing web development, I have been struggling with everything that requires some sort of design skills. Although I would love to have the ‘eye-for-design’ that some people have I am pretty sure I’ll never become an interface designer. Nevertheless, I think it is important for developers to improve their design skills.
I am pretty sure I am not the only developer suffering from this lack of talent. We can not all be that creatively talented but at least we can improve our design talent by checking inspiration sites on a fequent base.
Since the world wide web is pretty huge you might question yourself ‘where the heck do I start’?
There are tons of sites to visit and in my opinion it doesn’t always have to be the most popular site, as long as the websites/designs listed inspire you.
This is an overview of some of the well known design inspiration sites. Apart from these you can pretty much google around for some inspiration.
Award based top sites
- The FWA – this probably is one of the most famous sites, but in my opninion not the best reference to train your design skills. Most of the sites listed at The FWA are cool but just to fancy for us, developers.
- Awwwards – The Awwwards site itself is pretty good looking. Apart from that you may found some nicely designed sites over there.
- CSS Awards – CSS Awards provides a nice collection of CSS based designs. I have seen some less ‘wicked’ designs overthere. Nevertheless they are still a great addition to your inspiration.
- CSS Winner – Another list of great CSS site which also uses a “best site of the day” principe.
- CSS Design Awards
Non award based sites
- Web Creme
- Site Inspire
- MephoBox – MephoBox provides a great amount of design inspirations for some parts of your site (forms, buttons, …)
- Best Web Gallery – Gives a merged list of HTML and Flash sites.
- Design Snack
- CSS Remix
- CSS Elite
- Design Fridge
The sites listed as inspiration are not supposed to be ripped-off in any way, but only used as a reference for your own creativity.
Design inspiration can go a lot further then only website designs. There are several sites around which help you to get inspiration by providing a list of different graphics, pictures and visuals aswell.
In my previous post I have been showing three approaches to create a dynamic sidebar in ASP.NET MVC. Besides these three ways, I have also been trying to get this done using Ninject. Unfortunately this didn’t work (yet).
Recently I had a chat with my colleague Toon De Coninck, who pointed me into the correct direction to create a dynamic sidebar using Ninject.
The general approach in achieving this is the same as “Using a Sidebar base Controller and a Render method together with ModelBinding“. Only in this case we are combining modelbinding with dependency injection using Ninject.
In this example we are using the same objects as in the “Using a Sidebar base Controller and a Render method together with ModelBinding” example.
public abstract class Sidebar
{
public string Title { get; set; }
public IEnumerable<string> SidebarList { get; set; }
}
public class BlogSidebar : Sidebar
{
public BlogSidebar()
{
this.Title = "Blog Sidebar";
this.SidebarList = new[] { "Blog Category 1", "Blog Category 2" };
}
}
public class NewsSidebar : Sidebar
{
public NewsSidebar()
{
this.Title = "News Sidebar";
this.SidebarList = new[] { "News Category 1", "News Category 2" };
}
}
public class DefaultSidebar : Sidebar
{
public DefaultSidebar()
{
this.Title = "Default Sidebar";
}
}
We are also using the same SideBarBaseController and ModelBinder (but we are going to make some changes to this SideBarModelBinder):
public class SidebarBaseController : Controller
{
public ActionResult RenderSidebar(Sidebar sidebar)
{
// Using this method, we can create a view and pass the model to the view
return View(sidebar);
}
}
public class SideBarModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var controller =
controllerContext.RouteData.Values["Controller"].ToString().ToLower();
var action =
controllerContext.RouteData.Values["Action"].ToString().ToLower();
// The code below will be modified in this example
switch (controller.ToString())
{
case "blog":
return new BlogSidebar();
case "news":
return new NewsSidebar();
default:
return new DefaultSidebar();
}
}
}
As mentioned in that previous post, please do not forget to register the modelbinding in the global.asax.cs
ModelBinders.Binders.Add(typeof(Sidebar), new SideBarModelBinder());
Using Ninject
Basicly what we are going to do is replace the dirty switchcase (inside the SideBarModelBinder class) with some Dependency Injection using Ninject. So first of all, lets set up a ninject DependencyResolver.
To do so, add a class named NinjectDependencyResolver to your project and make sure it looks like:
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver()
{
kernel = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
public IBindingToSyntax<T> Bind<T>()
{
return kernel.Bind<T>();
}
public IKernel Kernel
{
get { return kernel; }
}
private void AddBindings()
{
// Here is the binding logic
Bind<Sidebar>().To<BlogSidebar>();
Bind<Sidebar>().To<NewsSidebar>();
Bind<Sidebar>().To<DefaultSidebar>();
}
}
Inside the AddBindings method we are binding all the available sidebars with its abstract Sidebar class. This way we can get rid of the dirty switch case and itterate each existing sidebar object (which is registered to ninject using the Bind method) using DependencyResolver.Current.GetServices<Sidebar>();.
Register this NinjectDependencyResolver class inside the global.asax.cs:
DependencyResolver.SetResolver(new NinjectDependencyResolver());
All that is left is to remove the switch case inside the ModelBinder, and replace it with the code below:
public class SideBarModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var controller = controllerContext.RouteData.Values["Controller"].ToString().ToLower();
var action = controllerContext.RouteData.Values["Action"].ToString().ToLower();
var sidebarName = controller + "Sidebar";
IDependencyResolver resolver = DependencyResolver.Current;
var sidebar = resolver.GetServices<Sidebar>().SingleOrDefault(sb => sb.GetType().Name.Equals(sidebarName, StringComparison.CurrentCultureIgnoreCase));
if (sidebar != null)
return sidebar;
else
throw new Exception(String.Format("No sidebar has been found for controller '{0}', make sure a sidebar class named '{1}' is registerd to the Ninject kernel", controller, sidebarName));
}
}
For each controller that inherrits the SidebarBaseController, this will look for a sidebar named [ControllerName]Sidebar. If no sidebar with this name is found, an exception is thrown.
As you can see I have chosen to take “convention over configuration”, since this is done almost everywhere inside APS.NET MVC. If you prefer to do different, just change the logic inside the BindModel method.
Recently I have been wondering about how to implement a dynamic sidebar (a sidebar which content can change depending on the controller or action), after a long conversation on twitter I came across three different ways to implement this:
- Using a Sidebar controller and @Html.Actionw
- Using a Sidebar base Controller and a Render method together with ModelBinding
- Using sections
I agree that not all three are following the guidelines. Nevertheless I decided to share them since they can be helpful someday.
The original discussion was how to implement sidebar behavior with dependency injection using Ninject. Because I didn’t manage to get it to work using Ninject, I tried using Modelbinding, which did work (since you can use controller-specific modelbinding). If anyone knows how to implement this using a IoC container, feel free to leave a comment.
Using a Sidebar controller and @Html.Action
When using this approach we will be creating a single Sidebar Controller with a single Action to handle the Sidebar rendering. This action will contain a parameter to define which Sidebar should be rendered.
The good part about this method is that your individual controllers (HomeController etc) do not need to know anything about your Sidebar. The Sidebar will be rendered in the views using the @Html.Action() method (where the action method will call an action inside the Sidebar controller).
To start, let’s create our Sidebar controller:
public class SidebarController : Controller
{
public ActionResult Render(string sidebar)
{
// You can choose to create one partial view for each sidebar type
// Or you can create one partial view and let the content be depending on the type, passed to the view
switch (sidebar)
{
case "Blog":
// Apply some logic to implement the Blog sidebar
// For this example I will simply return a partial view
return View("BlogSidebar");
case "News":
// Apply some logic to implement the News sidebar
// For this example I will simply return a partial view
return View("NewsSidebar");
default:
// Apply some logic to implement a default sidebar
// For this example I will simply return a partial view
return View("DefaultSidebar");
}
}
}
As you see, I have decided to create a view for each type of Sidebar, this is just to make it easier to demonstrate.
The different views simply contain a header tag to define which view has been loaded
<h1>Default Sidebar</h1> <h1>Blog Sidebar</h1> <h1>News Sidebar</h1>
All that is left now is to call this controller and action every time you want it to be visible, a great place to do so is inside the _layouts.cshtml but I do not really get how to make the sidebar dynamicly from within the _layouts.cshtml. To solve this, I decided to render the sidebars directly inside the views, like so:
@Html.Action("Render", "Sidebar", new { sidebar = "Blog" })
Using the above line, you should be able to render a different sidebar wherever you want.
Using a Sidebar base Controller and a Render method together with ModelBinding
The previous example (using a Sidebar controller and @Html.Action) required a extra parameter to be passed to the controller’s action. This could be a possible solution, depending on your requirements. Never the less I do not really like the fact that we are required to pass this parameter.
This method requires more code to be written but at the end it’s a lot easier to add extra sidebars, because the sidebar logic will be only at one place and one view (unless your application requires to use different views, I will explain everything using a single view).
To begin let’s create our Sidebar abstract class, BlogSidebar and NewsSidebar classes. These classes will contain the data required to pass to our view.
public abstract class Sidebar
{
public string Title { get; set; }
public IEnumerable<string> SidebarList { get; set; }
}
public class BlogSidebar : Sidebar
{
public BlogSidebar()
{
this.Title = "Blog Sidebar";
this.SidebarList = new[] { "Blog Category 1", "Blog Category 2" };
}
}
public class NewsSidebar : Sidebar
{
public NewsSidebar()
{
this.Title = "News Sidebar";
this.SidebarList = new[] { "News Category 1", "News Category 2" };
}
}
public class DefaultSidebar : Sidebar
{
public DefaultSidebar()
{
this.Title = "Default Sidebar";
}
}
Now that we have our Sidebar classes we can create the base Sidebar controller that has a single Action, expecting a single Sidebar parameter.
public class SidebarBaseController : Controller
{
public ActionResult RenderSidebar(Sidebar sidebar)
{
// Using this method, we can create a view and pass the model to the view
return View(sidebar);
}
}
Of course we are not going to pass a Sidebar instance each time we call this RenderSidebar action, we will use Modelbinding to do this for us.
public class SideBarModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var controller =
controllerContext.RouteData.Values["Controller"].ToString().ToLower();
var action =
controllerContext.RouteData.Values["Action"].ToString().ToLower();
switch (controller.ToString())
{
case "blog":
return new BlogSidebar();
case "news":
return new NewsSidebar();
default:
return new DefaultSidebar();
}
}
}
1
<p>As you can see, each time we require a Sidebar instance, the SideBarModelBinder will check which controller was requested and will return the corresponding Sidebar instance. Don't forget to register this modelbinder in the Application_Start method inside global.asax.cs</p>
1ModelBinders.Binders.Add(typeof(Sidebar), new SideBarModelBinder());
Right click the RenderSidebar action and create a view. For this example I have decided to use a strongly typed view based on the Sidebar model. Do not forget to put this view in the Shared folder, since it will be used by every controller.
@model SidebarDemo.Domain.Sidebar
<h1>@Model.Title</h1>
<ul>
@foreach (var listEntry in @Model.SidebarList)
{
<li>@listEntry</li>
}
</ul>
All that is left to do is create our controllers and call the RenderSidebar in the view wherever we want it to be shown. I have created a simple BlogController with an Index action and a corresponding, loosely typed, view.
public class BlogController : SidebarBaseController
{
public ActionResult Index()
{
return View();
}
}
If you didn’t create a view, do so. Else open this view and make sure to edit it so that it looks like the following code
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Action("RenderSidebar");
Since we are putting this code inside a view that is rendered using the BlogController, our ModelBinder will return a “BlogSidebar” to the RenderSidebar action inside the base controller.


It might not be the best way to achieve it, but it is definitely a great way to check your modelbinding knowledge !
Using sections
Using sections is pretty straight-forward, the only actions to take are creating the section inside your _layout file and defining it in your desired (or all) views.
Before modifying your _layout file to include a section definition, it is important to decide which behavior to implement when no sidebar is defined inside a view. You can show default content, or decide to leave out the entire sidebar.
I’d leave out the entire sidebar when it’s not defined, but this depends on your personal (or the client’s) needs. To do so, place the following lines inside your _layout.cshtml file:
@if (IsSectionDefined("sidebar"))
{
<div id="sidebar">
@RenderSection("sidebar")
</div>
}
If you decide to show default content when the sidebar is not defined, replace the above lines with the following lines of code:
<div id="sidebar">
@if (IsSectionDefined("sidebar"))
{
@RenderSection("sidebar")
}
else
{
<p>Default Sidebar</p>
}
</div>
The div with id=”sidebar” can be changed to whatever you prefer, I just used a div with id ‘sidebar’ for this example.
As you can see I specify the section name ‘sidebar’, this can be changed to any value (just make sure to use this new value in your view as well).
Now you have defined the section inside your _layout file, the last step is to actually feed the section with content. This is done inside any view (that is using this layout file of course) by adding the following code
@section sidebar{
<h1>Home Sidebar</h1>
<p>This is my sidebar content</p>
}
When this view (in my example it’s the Home\Index.cshtml view) is rendered, the page’s source will contain the following html.
<div id="sidebar">
<h1>Home Sidebar</h1>
<p>This is my sidebar content</p>
</div>
If you decided to show some default content when the section is not defined you should see this default content on every view that doesn’t define this section.
Great explanation of using sections can be found at: http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
Personal Favor
My personal favor for implementing a sidebar is using sections. This is the most documented way of achieving this. The other two examples where just experiments while discussing the best way to do so.
This is a quick blog post to show you how to add a custom action using c#.NET.
In some cases you programmaticly create a SPList which will require a custom action. If this custom action is required for only this SPList, I would advice creating this custom action using the following example:
SPUserCustomAction action = oList.UserCustomActions.Add(); action.Title = "MyActionTitle"; action.Description = "MyActionDescription"; action.Location = "Microsoft.SharePoint.ListEdit"; action.Group = "Permissions"; action.Url = "~site/_layouts/yourpage.aspx?List=" + oList.ID.ToString(); action.Update();
Using this example you should be able to create your own custom actions using C#.
SharePoint has a great column type: Lookup.
This column type will, as the name says, look up values in another list. It is used to link two lists to eachother (1-1 or 1-n relation).
The lookup column type is displayed as a standard dropdown list. But watch out, when the source list (the list from which the Lookup column reads its values) contains more than 20 items some things just don’t work as expected or don’t work at all.
When there are less then 20 lookup items, the column is displayed as a select control. No problem in this situation.
When the amount of lookup items is bigger then 20, the select controls is replaced by an input (text) field, an image (the dropdown arrow) and a select control (this select control is not visible at page load).
The reason they do this is because the user can type in the input field with auto complete (javascript). Since the user has to many values to select from a dropdown, this is a very powerful option in SharePoint (or at least it can be powerful if it worked properly).
When clicking on the image, the select control will pop up containing the lookup values you can choose from.. Clicking any value inside this select control will make this control disappear again. The input control will now contain the display value of the lookup value (the one the used clicked on).
Cascading Style Sheet
The first problem on this way of rendering the Lookup column (on + 20 items) is that the css will not work anymore.
After looking into the html I found that SharePoint positiones the select control (when clicking the image) using core.js.
The function in core.js is called FilterChoice(opt, ctrl, strVal, filterVal) this function will do more than positioning the select control. (this function also positions the lookup column with less then 20 items, although here is no css problem). Since the top and left css property is set everytime when a user clicks the image, we are not able to fix this problem using css. To fix this we should override the FilterChoice function.
[SOLUTION TO BE INSERTED]
Content Organizer
Apart from the css problem this alternative way of rendering the lookup column works fine. Atleast at first sight…
When you are creating Content Organizer rules based on a Lookup column (with +20 values) an even worse problem shows up.
Scenario’s
Creating a content organizer rule based on a lookup column with less then 20 items will work as expected. The rule is created and documents dropped in the drop off library containing this metadata will be routed to the destination list.
When you are creating a content organizer rule based on a lookup column with more then 20 items, the control will be rendered as mentioed above (input, image, select controls). Saving the rule will work normally but you will find out that the rule is not working. Files will not be routed when containing the metadata you’ve selected in the rule.
Editing the content organizer rule will tell you why… On the edit page, the value of the lookup column will be set to (none).
I’ve done hours of reflectoring and debugging (at run time) the microsoft assemblies and found that the following method is causing this behavior:
private BaseFieldControl GetBaseFieldControlForCondition(int clauseNum, int fcIndexWithinClause)
{
return (this.conditionControls.Controls[0].Controls[(clauseNum * this.availableColumns.Items.Count) + fcIndexWithinClause].Controls[3] as BaseFieldControl);
}
In the scenario when there are less then 20 lookup values, this BaseFieldControl will contain a value equal to the index of the value inside the dropdown list. When there are more than 20 items, the control will be rendered as mentioned above (input, image, select controls) and the value of the BaseFieldControl will be equal to 0. SharePoint will think this is the index of the selected value, therefor (none) will be saved (since this is the first option).
My guess is that Microsoft developers forget to make this function work with the special way of rendering the lookup column.
What is going wrong ?
Looking at the GetBaseFieldControlForCondition method, it is pointing to child controls of the “conditionControls” element. Inspecting the html of the masterpage (not in the browser, but on your filesystem) show us how this control looks like:
<table id="conditionControlTable"><tr><td id="conditionControls" runat="server"/></tr></table>
Initialy, this control contains no childs. At runtime, this control looks like (this html is based on my content type):
http://www.pastie.org/3303266
As you can see the control contains alot of children and the ID is replaced with
ctl00_PlaceHolderMain_conditionSection_addClauseLabel_conditionControls which is normal and has nothing to do with our problem.
The problem is that the GetBaseFieldControlForCondition will try to call the control containing the index of the selected lookup item which is stored in the value attribute. After doing some run-time debugging using reflector pro (which is an awsome tool btw!) I found out that, working with the special way of rendering a lookup column, will return a value of 0.
There’s no “object not set to an instance of an object” exception, so the control is found, but doesn’t contain the correct value.
Until now, I haven’t find any solution yet. Although my guess is it can be solved using a few Jquery lines to set the value attribute to the correct lookup index. Unfortunalty, I haven’t found which control needs to be set
Categories
- .NET Development (10)
- News (1)
- No programming (2)
- PowerShell (2)
- Sharepoint 2010 (25)
- Silverlight 3 (4)
- Silverlight 4 (2)
- UX (1)
- Windows Phone 7 (1)
Tags
approval ASP ASPMVC association BCS bug c# CBA Claims Client Object Model COM Deployment Design pattern Entity Framework eventreceiver Field Fields generics Google calendar Interaction javascript listadded Managed Metadata MethodNotImplemented MMS Model Binding Mvvm Office office 2003 PowerShell properties reflection runtime save conflict Sharepoint Silverlight Site column Site Url synchronous Unit Testing Windows Phone 7 WorkFlow WP7 Xaml xmlRecent Comments
- albernazf on Why mocking Entity Framework Context can be dangerous
- need support/materials for developing external lists with visual studio 2010 | Question and Answer on Deploying an External List using Visual Studio 2010
- Marc Blakely on Deploying an External List using Visual Studio 2010
- frederikprijck on Mocking Entity Framework using ObjectContext and database first
- Ben Anderson on Mocking Entity Framework using ObjectContext and database first

