In this post, I am going to cover how to create/add a visitor group into your solution via code. If you are not quite sure what a visitor group is, or if it's the right fit for your need, then I would recommend reading What Is A Episerver Visitor Group ? Episerver provides us several ways to interact with visitor groups; one way is the VisitorGroupHelper found in EPiServer.Personalization.VisitorGroups. This helper will check if the current user is valid for a certain visitor group. For example:
For this tutorial, we will mainly be focusing on the IVisitorGroupRepository
The visitor group repository provides access to standard functions like, save a visitor group, delete a visitor group, list all visitor groups and load a visitor group by Id. To create and save a visitor group we need to use the IVisitorGroupRepository and a VisitorGroup object.
The code above is quite straightforward. Get an instance of IVisitorGroupRepository from the Service locator, create a VisitorGroup and use the save method.
This code is all very well, but, I'm sure you will probably want your visitor group to do something useful. This happens by adding criterions to the visitor group before you save it using the IVisitorGroupCriterionRepository.
In order to add criterions to your visitor group in code, you will need to use the IVisitorGroupCriterionRepository. If you try to just assign one directly by newing up a criterion yourself when you try and save the visitor group you will get an Object Reference exception. Luckily, the IVisitorGroupCriterionRepository is pretty easy to use:
The code is pretty simple, IVisitorGroupCriterionRepository only exposes one method, the list method that gets all the visitor groups that have been defined in your solution. You can then use the TypeName property to return the criterion that you care about. Add the criterion to the visitor group is pretty simple:
In today's guide, we have used the IVisitorGroupRepository and IVisitorGroupCriterionRepository repositories. We can use IVisitorGroupRepository to get, save and update visitor groups. We can use the IVisitorGroupCriterionRepository to get all the criterions defined within the solution in order to attach them to a visitor group.