Category Archives: EPiServer

Presenting: Find My Content

My main project is a multi website solution where 16 different websites is sharing the same source code.

Sometimes when we need to change specific Content Type and find a strategy on how to migrate the changes it’s good to know how much that Content Type is used, and in what way.

How do you do that?

A way to to find how much it is used is to perform a simple SQL Query:

SELECT c.pkID FROM tblContent c
INNER JOIN tblContentType ct ON c.fkContentTypeID = ct.pkID
WHERE ... = '...' -- various ways to identify your Content Type using pkID, ContentTypeGUID or Name

And go to Episerver Edit Mode to see how the editor has worked with each content.

But to be able to run the SQL query, you will need to have access to the production database which makes things a little more annoying. Specially if you need to use VPN connections or similar.

Therefore I have created an Admin Tool called “Find My Content” where you easily can find all content based on their Content Types.

Listing all Content Types

findmycontent.PNG

Here you see how many items of this Content Type is created by clicking the Name.

Details of a Content Type

findmycontent standardpage.PNG

In the details you can see all Content of this Content Type and which language they are created in. There is also a shortcut that will take you to Edit mode for that specific Content.

How do I get it?

I’m waiting for a NuGet package to be published on Episerver’s NuGet feed. Otherwise you can find the code on my GitHub.

Update: It is now available in the feed: https://nuget.episerver.com/en/OtherPages/Package/?packageId=Toders.FindMyContent

What’s next?

This was just something I threw together since I got tired connecting to my client’s environments using VPN and Remote Desktop.

I’ve got some ideas to add references between the different content, filtering on values for specific properties and so on.

Do you have any other ideas that would be nice to have in this tool? Just give me a shout in the comments below.

Episerver Event Helper v3.0

Years pass and hopefully you learn something and become better!

One thing that have been poking on my conscience for a while is the old EPiEventHelper that I blogged about a couple of years ago.

What’s wrong with it?

There are two things I don’t like with it.

1) Unclear usage

I have seen that it has been some confusion with how to best access the content – using the eventArgs.Content or using this.

public class StandardPage : PageData, IPublishingContent
{
    public void PublishingContent(object sender, ContentEventArgs e)
    {
        // this is how to access the already cast instance of the content.
        StandardPage standardPage = this;

        //This is the content from the argument, needs to be casted to your Content Type. But to me it feels more correct.
        IContent contentFromArgument = e.Content;
    }

}

A common question is if the e.Content and this are two different instances (they are the same) and which one should be used (honestly I don’t have a recommendation).

2) Single Responsibility Principle

The second thing is that this implementation violates the Single Responsibility Principle. The class representing your Content Type should been seen as a View Model or Data Model and therefore it should not contain any behavior or business logic.

I have seen some examples where the logic found in the event is really large, making the Content Type class very messy and hard to understand.

Presenting – EPiEventHelper 3.0

What? Why 3.0?

Pavel Nezhencev already created a NuGet package with EPiEventHelper and later upgraded it to use Episerver 10, calling it version 2.0. If I want to publish my version with new features to NuGet.org I need to bump the version even further.

What’s new?

First of all I have stopped checking if the current Content implements the event interface. Instead I’m using to use the IoC container in Episerver where you as a developer can add your own things.

This means that you will need to decorate your implementations of the interfaces with the ServiceConfiguration attribute.

[ServiceConfiguration(typeof(IPublishingContent))]
public class PublishingContentEvent : IPublishingContent
{
    public void PublishingContent(object sender, ContentEventArgs e)
    {
        IContent content = e.Content;
        var standardPage = content as StandardPage;
        if (standardPage == null)
            return;

        // Do something with your standard page
    }
}

Breaking change: This also means that if you are using the previous version of EPiEventHelper, you can no longer refer to the content using this!

public void PublishingContent(object
    sender, ContentEventArgs e)
{
    this.Name = "Hello World!";
}
public void PublishingContent(object
    sender, ContentEventArgs e)
{
        e.Content.Name = "Hello World!";
}

Breaking change: The interface does not know anything about the class representing your Content Type and therefore you will need to cast e.Content yourself!

public void PublishingContent(object
    sender, ContentEventArgs e)
{
    this.Title = "Hello World!";
}
public void PublishingContent(object sender,
    ContentEventArgs e)
{
        var content = e.Content as StandardPage;
        if (content == null)
            return;

        content.Title = "Hello World!";
}

Unless…

I have created a workaround for this where you can have the same pattern to bind the Episerver events, but only apply if to specific Content Types AND the Content will also be typed!

New functionality: Each interface have an abstract base class where you specify which Content Type class you want to use. As usual you use the ServiceConfiguration attribute to bind your implementation to the event.

[ServiceConfiguration(typeof(IPublishingContent))]
public class PublishingStandardPage : PublishingContentBase<StandardPage>
{
    protected override void PublishingContent(object sender, TypedContentEventArgs e)
    {
        // Here you can access the standard page
        StandardPage standardPage = e.Content;
    }
}

You can also specify if the Content that the event applies to needs to be the exact Content Type or that the class would inherit from it by overriding the boolean property AllowInheritance.

protected override bool AllowInheritance { get { return true; } }

Tests

I’m still learning how to best create tests with Episerver, so I have added a Test Project where I want to test if the events are bound and unbound properly.

I have also added some tests to make sure that I have not missed any interfaces or classes. The project is found in the same GitHub Repo.

You’re welcome!

I would really recommend that you take your time to extract the code for your events from the Content Types.
Just putting the ServiceConfiguration attribute on your Content Types would instantiate the class in a way that doesn’t always play well with Episerver.

I’m planning to update the NuGet feed with my new version! Keep your eyes open for updates in Visual Studio if you have used the previous version.

Removing all translations – Part I (understanding the Episerver Database)

Me and some colleagues had a project where we needed to remove all translations from an Episerver website except one.

For that we needed to know what the database structure looks like in Episerver and I will share this to all of you!

Now I’m trying out something new – a video post! I know it’s not the best quality but it’s a start.

In this video I will describe some of the most important tables in the strucuture and how they are related to each other.

I hope you like it! Please add some comments for questions or feedback.

Planning your Episerver project

You’re going to start working on a brand new Episerver project! Your solution is a brand new slate where you can add your best code ever and you just received the design specs and requirements!

xmBjXcm.gif

Now you need to sit down and get an idea how to build your solution. But where should you start?

In this blog post I’m trying to give some hints of how I use to plan building an Episerver website. Since the sales, concept and requirement phases can be very different from company to company (and sometimes even project to project) I will try to keep to a very fundamental level.

First of all I’m asking myself the following questions:

What do I want do to?

Get an idea of what the solution should solve and which functions that is needed.

giphy-1.gif
The answer to this could be “a website” – but what should it contain? News articles where the user can list and filter based on categories and date? Product presentation where you can rate each product? Logged on functionality with profile presentation?

Sometimes the requirements from earlier phases in the project already have this but I’ve seen lots of requirements which are still on a concept level rather than a functional spec.

Try to summarize a map of functions from an abstract perspective and leave out the details for now.

My example throughout this post have

  • Customer profiles.
  • Product presentation.
  • Authenticate to edit their profile.
  • A customer can also rate news. In the future maybe even products so let’s keep that function isolated.

scope.png

Using the SOLID principles, this could maybe become the start of your architectural design of functionality in the project as you want to separate the functions.

What areas are Content logic vs Business logic?

When I say Content Logic I refer to things you can do within your CMS’ API such as listing, filtering and reading content based on what is created by the editor while Business Logic would be connected to other data and functionality from systems or databases than your CMS.

Looking at the defined functions from the image above, I define what I can do in Episerver in terms of data structure, and what comes from other systems.

Example how to define: Your page displays a list of links but you don’t know where they are stored:

  • Should the editor just add links using the Link Item Collection, Content Area or the XHTML property in Episerver?
  • Should the list automatically be fetched from the content in Episerver (for example children to a specific page)?
  • Should the list be fetched from an external service such as Delicious, Pocket or similar?

The first options would be Content Logic while the second one is Business Logic.

Based on the functions in the image above and what I know so far I can start marking which sections are Content or Business.

business vs content.png

Also remember to start focus on the areas that are critical for the project, the other things can usually be decided later on (especially if you’re working agile).

From this I would start with the content logic to see how to structure these.

Content – because it’s a website!

What is the content structure?

When I have decided which areas comes from the CMS, I would try to define what parts I would need to create in Episerver based on the design specs and requirements.

Example how to define: The “normal page” and “news article page” are visually identical, except that the “news article page” also have images.

  • Should I create two separate page types?
  • Should I only create only one page type, but be able to add the image list as a block?
  • Should I only create one page type, as the normal page might also be able to have an image list?

 

How the editor would work with the content has a large role in my decisions as well as how it can be generalized and reused to minimize the headache for the developers in the future.

I try to make pages as generic as possible. To have many very similar content types will in the end become hard to maintain since they could have the same functionality.

Having a modular approach is quite nice for that, although it can get quite messy for the editor if there are hundreds of block types to choose from.

Another trick is to find a structure where you restrict enough for the editor, while still letting the editor be able to be creative and have freedom with their content. This is a very hard thing to find!

My suggestion is to have a simple data structure and look at how to simplify the editor experience using EditorDescriptors and maybe even Dojo. Sometimes you can even use the Edit mode to make a better Editor experience than the Properties mode.

So based on the “News” section in the image above I would structure the implementation like this.

content logic.png

Where the normal “Data Layer” in a three tier is the Episerver API. In the Content Logic I build functionality to filter and sort the content and the presentation is the usual Views and frontend resources.

Content – How should everything be rendered?

To start with, try to keep the rendering of your website as a normal “.net website” as much possible using Episerver as the data container.

I would recommend that you use the EPiServer:Property web control (WebForms) or PropertyFor HTML extension method (MVC) when rendering properties and content.
You’ll get tons of nice features with RenderSettings, Tags, Display Options, Display Channels and just to name a few.

When it comes to tweaking your rendering, the Alloy project has quite a lot of examples, however they are no documentation on why, how or exactly to use these and which code is related to which functionality. Don’t refer too much to Alloy templates as it would be overkill for a normal content website.

Business Logic – because I have lots of complex things to build!

Here is a nice part about building an Episerver website – basically it’s like building a normal .NET website where you’ll get a great API for your content (and an interface for your editors to work with that content).

For the other logic you can add tools like Entity Framework, IoC containers, external web services or other stuff you like to play with! Mostly I recommend using a 3 tier approach where you separate data from logic.

Once I have figured out the functionality that does not directly concern content, I look at how I can fit the presentation in Episerver.

There are three common approaches to present external data:

  • Import all data as content using a scheduled job or similar.
  • Create a content type for your data, but use keys in the context (QueryStrings or Routing) to identify which data item to display.
  • Use a Content Repository which is a built in tool in Episerver that handles content structure, routing, access rights and so on for programmatically.

Normally I would go for importing the data or using a Content Repository.

Based on the “Products” section in the image above, I would structure the implementation something like this.

business.png

Where I read and save from my own database or external sources in the Data Layer, creating business logic that handles the Data Layer in “Business Logic” and glue this together with Episerver in the Content Logic.

On top of that I would have the presentation layer as usual with Views and frontend resources.

There is one thing you should keep in mind though!

Don’t make your solution too dependent on external systems – have a fallback plan

closed.png

When your website loose connection to an external service that provides information make sure that it does not go down.

For example store the information locally so that it can be used when the connection is lost, or display a sign that tells the visitor that all areas of the website are not working at the moment.

Unfortunately I don’t have a silver bullet solution on how to present your data, but as long as you don’t start throwing lots of 500 (specially not on the start page) and that reading the external data does not make the website slow.

Logic finished – now what?

Normally I work in agile projects (based on how we can work with the client), at least we split most of our project into iterations or sprints.

i.chzbgr.gif

Most of the time, the customer wants to be up and running with the content work as soon as possible, so in the first iterations I try to plan the most common content types that they will work with.

Creating an MVP

In the example above I would have Henric Kniberg’s example of creating a MVP (minimum viable product) and start working with the basics that are less automated.

  • News
    The editor can create news articles but the listing would either be a very basic one or even be created manually by the editor.
    Automatic listing with filters would be created in a later sprint.
  • Products
    Say that I decided to go for the “import all products as pages” approach.
    I would prioritize building the product pages so that the editors can create some examples that they give feedback to.
    I would create the product import in a later sprint.
  • Profiles
    I will create the content types necessary, but after the first sprint the customers needs to contact support to change these.
    Authentication would come later, and then I can look at letting the customer update their profiles.

Ok I admit that this is a very simple priority! Pushing more complex sections such as product import and authentication to later sprints means there is a risk that they won’t make it to launch.

But this is a rough plan based on that the only priority for the customer is to start working with content.

However I want you to keep in mind that take small steps instead of building the entire project at the same time.

Summary

So! Thank you for following me through this article. These are some major thoughts I have on how to plan an Episerver project.

So a short recap

  • An Episerver website is simply a .NET solution where you get an API to fetch content (and an interface for the editor to work with the content).
  • Build your system integrations separately and integrate them using the Episerver API.
    • Make sure that your site does not crash because your integrations can’t integrate.
  • Start of simple and add the more complex parts later.

If you don’t agree of want to add to my list, please add a comment below.

bye.gif

How to NOT use properties on Content Types

I’ve seen more and more examples on how to NOT use properties on your Content Types – setting visit/Request specific information to them.

My example below is a very harmless, but I’ve seen examples where the price for an e-com site is set like this!

How do you mean?

The example would be to display the visitor’s IP, which is common to be different for each request.

First of all we have a Block Type:

[ContentType(GUID = "5597f215-f5cc-4fd0-bcff-eb06a44fc343")
public class MyPage : PageData
{
    public string MyProperty { get; set; }
}

And the controller set’s the value:

public class MyPageController : PageControllerBase<MyPage>
{
    public ActionResult Index(MyPage currentPage)
    {
        currentPage.MyProperty = Request.UserHostAddress;
        return View(currentPage);
    }
}

And a view displays it:

@model MyPage
Name: @Html.PropertyFor(m => m.Name)
IP: @Model.MyProperty

But what’s the problem?

The problem is that each instance of MyPage is cached and could basically be referred to as “static” – when a value is set to MyProperty, the value is set for all visitors.

For example when visitor A visits from IP address “192.168.0.10”, MyProperty is set with the IP. When visitor B visits from “192.168.0.11”, MyProperty will still have the value from visitor A until the controller sets the IP from visitor B.

Or even worse: When the the visitor A comes to the view and MyProperty is rendered there is a chance that visitor B comes to the controller and sets a new value to MyProperty – so that the view will render the IP from visitor B.

I’m sorry for the crappy GIF, but hope you get the point ;)

properties

So what should I do?

Make sure that you have a specific class that contains your information and create a new instance of this class for each Request. For my example I would have a viewmodel instead. In Episerver projects the ViewModel could also contain the Content itself:

[ContentType(GUID = "5597f215-f5cc-4fd0-bcff-eb06a44fc343")
public class MyPage : PageData
{
}

public class MyPageViewModel
{
    public string MyProperty { get; set; }
    public MyPage CurrentPage { get; set; }
}

With the Controller

public class MyPageController : PageControllerBase<MyPage>
{
    public ActionResult Index(MyPage currentPage)
    {
        var viewModel = new MyPageViewModel
        {
             MyProperty = Request.UserHostAddress,
             CurrentPage = currentPage
        };
        return View(viewModel);
    }
}

And with the View

@model MyPageViewModel
Name: @Html.PropertyFor(m => m.CurrentPage.Name)
IP: @Model.MyProperty

Again this a simple example, but say you’re having an e-com solution and want to display the price. You don’t want to display other visitor’s prices don’t you? ;)

Where to integrate with Episerver Forms

If you want to control what’s going on when a form created with Episerver Forms is submited, there are different areas you can implement your logic. The most usable ones (or the ones most people would go for) would be Controllers where the submitted form is posted, the implementation of DataSubmissionService, various Events and through Actors.

So which one should you use? It all depends on what you want to do and here are my thoughts on where to integrate depending on what you want to do.

So what are these?

First we’ll do a quick check on the different areas I mentioned.

lifecycle

Controllers

First of all, Episerver Forms use two Controllers that receive data from the posted forms.

DataSubmitController

This one is called with the out of the box Javascript-driven functionality that makes an AJAX request with the form data. This requires the visitor’s browser to be able to use Javascript.

To replace this controller, the easiest way would be to change the path with coreController configuration in \modules\_protected\EPiServer.Forms\Forms.config.

There are some other ways but that would require that you create your own Javascript-functionality for the form, which would require that you create your own rendering Controller for FormContainerBlock (see below) that does not output the OOTB Javascript references.

FormContainerBlockController

This is if you have turned off the Javascript-support using the workInNonJSMode configuration in \modules\_protected\EPiServer.Forms\Forms.config or if the visitor’s browser does not have Javascript support.

To replace this controller you’ll need to create your own rendering Controller and make sure that it is used instead of the original FormContainerBlockController.

DataSubmissionService

This class is used by the Controllers and takes care of the submitted data, validates and stores it. It is registered into Episerver’s IOC with the usage of EPiServer.Forms.Services.DataSubmissionService.

You can simply replace it by creating a ConfigurableModule. However as it handles quite alot of the nice stuff to interpret the submitted information from the forms, I would recommend to not play around too much here.

Events

As I mentioned in my previous post about Episerver Forms, there are some Events that you can hook up to:

  • FormsSubmitting
    Before each step, at least once
  • FormsStepSubmitted
    After each step, at least once
  • FormsSubmissionFinalized
    When final step is posted
  • FormsStructureChange
    When a Form Container Block is published

Events were the most common way in XForms to take care of the data that was submitted from the form, for example if you want to save or send it somewhere.

Actors

Actors are the ones that do the final actions when submitting the form. They implement the interface IPostSubmissionActor and the built in actors are SendEmailAfterSubmissionActor and CallWebHookAfterSubmissionActor.

The simplest way to create your own Actor is to create a class that inherits PostSubmissionActorBase.

As you’ve seen with the WebHook and E-mail actors, you can also create your own interface to customize the Actor from the editor interface but I don’t have any examples for that right now.

Thanks for the update, but I still don’t know which I should use?

Controllers

Given the various options I would rarely touch the Controllers since they manage both the initiation and rendering of your forms.

If you’re daring enough to replace the overall rendering, for example when it comes to the Javascript based submits, go ahead and create your own FormContainerBlockController.

From a rendering point of view the FormContainerBlock is nothing more than a block that has a Controller with a TemplateDescriptor attribute. These are stored as TemplateModels in the TemplateModelRepository and can be modified there using an InitializationModule.

DataSubmissionService

Here all the nice stuff to interpret the posted data, store files and so on, so I would try to keep this intact.

The only good reason I’ve heard where it would be necessary to replace the DataSubmissionService would be to override where uploaded files are stored.

Events

This is the classic way to read and do something extra with the posted information. It still works, but I would say that if you want to save or send the data at the end station of the cycle, this would not be here.

Here I would recommend that you read or modify the data if needed, but don’t perform any actions based on it.

Actors

This is where the train stops and all Actors that are interested in the data from the form do what they are supposed to do. If you’re going to send extra information to an external service I would suggest you do that here.

Summary

I haven’t worked with Episerver Forms in a live project yet, but at least these are the areas I would suggest you can use. If you have any ideas or more tips, feel free to add a comment below!

Episerver Forms: How to change where uploaded files are stored

During my session about Episerver Forms at the Øresund Episerver Developer meetup I received a question about how to change where uploaded files are stored

A quick look at how Episerver Forms manage the posted information I found that it is the DataSubmissionService that creates an Asset Folder and stores the file.

assetfolder

By replacing the original DataSubmissionService with a custom one that overrides the method StorePostedFile I could easily decide for myself where to store uploaded files.

Take a look at my example from GitHub.

Change access rights for Episerver Find UI

As you probably know, Episerver Find has a UI where the editors can see statistics on how their visitors use the search functionality, fine-tune their search results by adding best-bets, related queriessynonyms and boost results as well as get an overview what kind of information is indexed in the Find Index.

To see the menu items in the Episerver Find UI, the user needs to be a member of the following roles: “WebAdmins”, “Administrators”, “SearchAdmins” and these applies to all of the views: Manage, Configure and Overview.

To start with, see if you can setup your users and roles so that only those that should have access to the Find views are has any or these roles.

But I can’t!

Ok, let’s see how we can change this!

These roles come from the property AllowedRoles from EPiServer.Find.UI.FindUIConfiguration which is registered in the IOC for EPiServer.Find.UI.IFindUIConfiguration.

finduiconfiguration

How do I change this?

If you want to change this, you’ll need to change the registration for IFindUIConfiguration to your own implementation. This is easily done as I did with a “ConfigurableModule” my previous blog post about replacing the IContentTypeAdvisor registration.

However I only want to change the property “AllowedRoles” and looking at EPiServer.Find.UI.FindUIConfiguration I can see that the property is not virtual. Hence I can’t make my custom implementation inherit from the original implementation and just override AllowedRoles.

nosuitable

That shouldn’t be a problem? Just add new or copy the entire class!

I could solve that by writing public new string[] AllowedRoles but that is rarely a good practice!

So is copying the existing class and only change the AllowedRoles property, I don’t want to check that my custom implementation is in sync every time I update Episerver Find!

So I’m gonna make sure that my custom implementation wraps the original implementation in a private field.

public class WrappingFindUIConfiguration : IFindUIConfiguration
{
    private readonly IFindUIConfiguration _originalFindUiConfiguration;

    public WrappingFindUIConfiguration()
    {
        _originalFindUiConfiguration = new FindUIConfiguration();
    }

    public string AbsolutePublicProxyPath()
    {
        return _originalFindUiConfiguration.AbsolutePublicProxyPath();
    }
}

This looks better except that I’m now always counting on that Episerver will use the Episerver.Find.UI.FindConfiguration and that it will have an empty constructor.

Reuse the original implementation

To start with, I will create a constructor in my custom implementation that takes IFindUIConfiguration as parameter and set it to the private field. This can be seen in WrappingFindUIConfiguration.

Secondly I will need to make the ConfigurableModule do some more things before replacing the registration.

  1. Find the current registration of IFindUIConfiguration
  2. Remove it from the registration
  3. Register my custom implementation and make sure to use the constructor that takes the IFindUIConfiguration parameter.

To try this out without creating roles, you can simply add a virtual role that is valid as long as the user is member of WebAdmins or Administrators:

<configuration>
    <episerver.framework>
        <virtualRoles addClaims="true">
            <providers>
                <add name="MyCustomFindRole"
                     type="EPiServer.Security.MappedRole, EPiServer.Framework"
                     roles="WebAdmins, Administrators"
                     mode="Any" />
            </providers>
        </virtualRoles>
    <episerver.framework>
<configuration>

 

Customize “Suggested Page/Block types” when creating content

I’ve found a neat way to improve the editor experience – IContentTypeAdvisor and it can be found in the EPiServer.Cms.Shell.UI.Rest namespace of the assembly EPiServer.Cms.Shell.UI.dll.

This interface is used to populate the list of suggested Content Types when creating new content.

This interface has one method GetSuggestions which returns an collection of ids of block types and takes the following input parameters:

  • iContent Parent
    The parent item where the editor wants to create the new content.
  • bool contentFolder
    This is true if the editor is creating your new content within a Content Asset Folder.
  • IEnumerable<string> requestedTypes
    This is a list of the kind of content to create. The value comes from the UI and therefore they are just strings like “episerver.core.blockdata” or “episerver.core.pagedata”. If created through a component in the asset pane it can also have the value of the CreateableTypes.

The default implementation in Episerver is to suggest the same content types as already created.

defaultcontenttypeadvisor
An example of usage would be to help the editor create a slideshow where the slideshow including each slide in it are blocks.

So what I want to do is to suggest the Slide block if the editor already has created a Slideshow block in that same folder.

CUT TO THE CODE

First of all I’ve have some new Block Types, one for the Slideshow that has a ContentArea where you put each slide represented by a SlideBlock.

And I will need to create an implementation of the IContentTypeAdvisor.
[ServiceConfiguration(typeof(IContentTypeAdvisor))]
public class ContentTypeAdvisor : IContentTypeAdvisor
{
    public IEnumerable<int> GetSuggestions(IContent parent, bool contentFolder, IEnumerable<string> requestedTypes)
    {
        ...
    }
}

Note that I’m registering this to Episerver’s IOC using the ServiceConfigurationAttribute. This is to tell Episerver that I want to use this implementation.

Episerver looks for all registered implementations of this interface instead of just 1, therefore I don’t need to do anything with the previous registrations (unless I want to, see further down).

What I want the advisor to do is check is whether the parent has any children that is a Slideshow block. If so the advisor will suggest the Slide Block.

bothadvisors
This is quite easy as can be seen in my SlideshowContentTypeAdvisor.

It is also a good practice to check whether the suggested content type (in this case the Slide Block) is available as child to the content parent and that the editor has the proper access rights to create a Slide Block).

But I want to use my Content Type advisor INSTEAD of the Default one?

It’s easy to remove the already registered implementation of IContentTypeAdvisor by implementing the IConfigurableModule interface, remove the current registrations and to register your own implementation instead.

slideshoadvisor

Look at my DependencyResolverInitialization for that.

Disable the “Suggested Content Types” feature

Look at DependencyResolverInitialization and just don’t register your own IContentTypeAdvisor after ejecting the existing registrations.

This will remove all registered implementations and your editor will never see any suggested content types.

noadvisors

Tweaking and extending Episerver Forms – Part 2

This is a blog version of the presentation of Episerver Forms called “Episerver Forms – the new black?” I had on the Episerver developer Meetup in Stockholm February 9.

Episerver Forms was released from its beta stage just a couple of days earlier so we could take a look at what the final version looks like.

I will here cover the basics but you can find some more documentation on http://world.episerver.com/add-ons/episerver-forms/.

I have also updated my GitHub repository https://github.com/alfnilsson/EpiserverForms with my findings.

XForms – Out with the old …

First I had a quick review of the current editorial form management part of Episerver – XForms.

The Wikipedia article on XForms describes that it “is an XML format used for collecting inputs from web forms”, the first version standardized 2003 and the latest update was 2009.
Episerver took this standard and implemented it as a way to store the form specifications in Episerver CMS 4.60. However it has some good parts as well as some parts that leaves us wishing for more.

Pros

XForms

The Editor UI for XForms

  • The specifications for XForms is standardized format, meaning you can import and export them between other systems that support this standard.
  • Using a user interface, it’s easy for editors to create simple forms.
  • Developers can extend submitting and rendering using delegates & events.
  • Submitted information from the visitors can be exported to Excel (and XML) files.
    What I think is amusing is that the file is only a file containing a HTML table saved into a file with the file extension .xls, but Excel can handle it.

Cons

markup

Sample markup from an XForm

  • The forms that can be created are very basic!
  • Also the editor UI is very rudimentary
  • There are no language or versioning support
  • It is hard to organize the forms as you only have a one level folder system.
  • The rendering of the forms that you get out of the box use very bad markup with tables.
  • XForms is an old standard

… in with the new – Episerver Forms

The new editorial form management in Episerver is simply called Episerver Forms. As a developer you install it as a add-on from Episerver’s Nuget Feed. In November 2015 it became available as a beta and released live on Friday February 5 with Episerver – update 99.

I really like the fundamental idea in Episerver Forms where the specification of the form including the form fields is stored as Content, which means that rendering the form is made by the normal templating system in Episerver.
However I don’t agree on some other parts on how the form is managed.

Pros

forms

The editor UI for Episerver Forms

  • As Episerver Forms is based on Content, you also get some of the fundamental concepts in the same package such as
    • Versions
    • Localization
    • Folder structure
  • Built in form “fields”
    • Multi step forms
    • Upload files
    • Captcha
  • Submitted information from the visitors can be exported to XML, CSV & JSON
  • Built in support for confirmation and notification e-mails
  • Developer can extend submitting using web hooks and delegates & events
  • Developers can extend rendering using Views
  • Developers can create custom field types using BlockTypes
  • Developers can extend what to do when form is submitted by creating custom Actors.

Cons

  • Keep in mind as Episerver Form creates contens as you’re adding form and form elements. This might break content based license models.
    For Episerver Find you will manually need to tell Episerver Find to not index Form Container Blocks and
  • Out of the box JavaScript based with AJAX posts
  • Compromises and workarounds

So what about the new stuff?

Creating a form using the editor UI

forms ui.png

Creating and editing forms is basically the same as creating and editing Blocks.

The form itself is a Form Container Block (EPiServer.Implementation.Elements.FormContainerBlock) and the form elements inherits EPiServer.Forms.Core.ElementBlockBase.
Each element will be stored in the Form Contain Block’s Content Asset folder.

However the editor UI makes the block-part a bit abstract for the editor as there is a new component in the Assets Pane called Forms (1 on the image above).
This component is basically just a shortcut to the folder called “Episerver Forms” and here you can only create new Form Container Blocks and folders (2 on the image).

Form content and elements

As you’re editing your form, you can easily add new elements using the Gadget “Form Elements” (3 on the image) that automatically opens and drag them to the Content Area of your form (4 on the image).

There are also some content possibilities where you can add a heading and a description.

Form settings – Content tab

all properties

Switching to “All properties” you will see some more settings and content that you can apply.

Filling the field “Confirmation message” (2) displays an alert, for example “Are you sure you are ready to post?” (will not work without JavaScript)

After submitting the form, do you want the visitor to stay on the same page and replace the form with a “thank you” message, or redirect the visitor to a specific page? Set this in either “Display page after submission” (3a + 3b).

You can also add some behavior settings such as allowing anonymous (not logged on) users to submit the form and allowing same users to submit the form multiple times. Personally I always forget to check these ;)

You can also allow the submitted information to be read using the Service API.

Don’t ask me what you would do with Categories on forms though, this is built-in on all Blocks but can be hidden using this little hack.

Form settings – Settings tab

Settings

In the Settings tab you can set what you want to do when the visitor submits the form. In XForms this was something you set on the submit button but will now be something set on the actual form.

Storing data

First and foremost you can set that information should be stored. Form submissions will then be stored in the Dynamic Data Store (DDS) but there is an API that can be used to read the information.

view submitted

Stored data can also be seen and exported in the view Form Submissions.

Actors

You can add your own “actors” that will act on incoming information.

There are two built in actors that you can use but you can create your custom ones as well.

E-mails

In these e-mails you can set sender, recipient, subject and the message. All these fields can use “placeholders” that will fetch data from the visitor’s form submission.

email

Note that you should allow the server to send e-mails from the sender domain or there is a risk that your messages are classed as junk. This is done setting up a DKIM authentication.

Web Hooks

You can provide Web Hooks where the server will send the submitted information.
This will send the submitted in a JSON serialized format which is quire cryptic. I will mention this further down in the section about events.

Configuration

You can customize some parts of Episerver Form with configuration.

<episerverforms minimumAccessRightLevelToReadFormData="Edit"
	sendMessageInHTMLFormat="true"
	defaultUploadExtensionBlackList="asp,aspx,asa,ashx..."
	coreController="/EPiServer.Forms/DataSubmit"
	formElementViewsFolder="~/Views/Shared/ElementBlocks"
	workInNonJSMode="false"
	injectFormOwnJQuery="true">
  • minimumAccessRightLevelToReadFormData
    Set what level the editor requires to read the submitted information. For example read, or administer
  • sendMessageInHTMLFormat
    Do you want e-mail messages to be sent as HTML or plain text?
  • defaultUploadExtensionBlackList
    You can blacklist file types that should be available to upload using the File upload element (see below).
  • coreController
    Do you want to use another controller when submitting the form? Set the path here.
  • formElementsViewsFolder
    Set where you want to have your custom view templates that overrides the ones built in.
  • workInNonJSMode
    Do you want the form to work without JS? Who doesn’t so I don’t really understand this would be an opt-in? See more about my thoughts concerning the non-JS fallback below.
  • injectFormOwnJQuery
    As the template for the form is using JQuery you can tell Episerver Forms not to inject the library (a quite old version 1.7.2).
    This would be to prevent your own website’s JQuery to conflict with the one injected by Episerver Forms.

Working without JS

During BETA, the Form required JavaScript to work. Mainly to get the multi-step to work, but also to submit the form.

After multiple requests to make Episerver Forms to work without JavaScript, Episerver added a configuration setting to make this work.

And the “fallback” isn’t even good!

but-why.gif

Setting the configuration workInNonJSMode to “true” will make the form to make a good old HTTP POST Request to the controller.

If the submitted information does not validate, for example required fields are not filled or validation on e-mail addresses, the controller redirects the user back to the page containing the form with some querystrings that includes the problem.

non js

Not only can the querystring be modified to say something else, the field that the visitor had posted are cleared.

Refreshing the page after a successful or unsuccessful submit will also continue to display the message.

Extend rendering

The built in views are stored in the folder modules\_protected\EPiServer.Forms\Views\ElementBlocks and have the name as the BlockData class representing the element, for example TextboxElementBlock.ascx.

As you can set a folder for your custom views and override the existing ones, all you need to do is to add a partial view with the same name as the original.

Look at my custom view _TextboxElementBlock.ascx, rename it to not start with an underscore and it will be used to render Textbox elements.

The built in views are ascx files for Web Forms but the work in MVC websites as well.

Extend element types

It’s very easy to create your own element types. So easy that there already are some blog posts about it. By Arve Systad and by David Knipe.

select map.PNG

I made my own element type for my presentation that allows the visitor to select a location on a Google Map.

For this example I created a block type MapElementBlock and a view for it.

I used the JQuery plug-in “JQuery Location Picker” which meant that I needed to add a JavaScript file, insert it into the Bundle Config and add a reference to the Google Maps API into the layout.

To finalise the editor experience I needed to add a translation for my new content type.
Otherwise newly created form elements of this type will have a name that is an error message from LocalizationService about not being able to find a translation.

Built in fields

There are some nice fields that you can use. These does not exist in XForms and the customer’s were often asking the Episerver partners if they can be added (with some headaches and work they could)

File upload

A simple file upload form.You can set valid file types and a maximum file size.

The uploaded file will be stored in the Content Asset folder for the block representing the File Upload-field, just don’t rename them as the connection to the submitted data will be lost..

inception.png

This means that the file will have the same access rights as the File upload element, which in turn will have the same access rights as the form it belongs to.
Inception anyone? :)

Captcha

captcha

There are many ways to create a Captcha, this is a simple one that will create an image, and validate that you entered the text that was “visible” on the image.

Multiple steps

A simple way to create a step-by-step wizard. For each step the visitor completes, the information will be saved. You don’t need to wait for the visitor to finalize the form to see the information from the completed steps.

steps

You can also setup rules to display steps for visitors that entered specific values in values from previously completed steps.

multi step rules

Predefined lists

You can create predefined lists so that the visitor can select values based on something dynamic. This is used by creating a “FeedProvider” that implements EPiServer.Forms.Core.ExternalFeed.IFeedProvider.

Episerver Forms has a built in that can read from XML Feeds such as RSS. In Forms.config you can easily try one using the Episerver World Blog RSS Feed.

Extend submitting – events

You can extend what’s going on when submitting a form by hooking up to these delegate events:

  • FormsSubmitting
    Before each step, at least once
  • FormsStepSubmitted
    After each step, at least once
  • FormsSubmissionFinalized
    When final step is posted
  • FormsStructureChange
    When Form Container Block is published

Submitting forms

For each time the visitor submits the form or goes from one step (see multiple steps above) to the other, the FormsSubmitting will be fired.
As there is a built in multi-step support, FormStepSubmitted will always be fired at least once.
Once the customer submits the form, FormSubmissionFinalized is fired.

The data in the event arguments are a bit cryptic to determine which value belongs to which field.

submitted

For example my element Name” has the key “__field_182” as the Block representing this element has the Id “182”.

You can use my InitializationModule to see what kind of information is posted.

Change structure

As the Form stores the information in the DDS, the structure of the Store needs to be altered when you change the form structure (adding, removing, changing order of fields).

FormStructureChange is an event where you can listen to these activities.

Summary

I really like the concept with Episerver Forms, especially that it is based on Content and Templates.

However I see that there are flaws and compromises in the implementation of posting data. I hope this gets a look at in a version 2 in the near future.

I’ve got some ideas on how to make Episerver Forms to make a classic “Post to yourself” kind of Form that I hope I get some time to put it in code soon.

Take a look at my GitHub repository and feel free to give me some feedback with things you like/dislike with Episerver Forms. I would really like to hear if you have your own workarounds or ways to play around with the new Episerver Forms.