How to create a new instance of a dependency inject object

I decided to write this post after seeing it done wrong on a number of occasions and also not finding many great examples of how it should be done. Most articles of DI or IOC tend to focus on objects such as a logger being injected and then calling functions on that object.

Take for instance, this example in the Simple Injector documentation:

using System;
using System.Web.Mvc;

public class UserController : Controller {
    private readonly IUserRepository repository;
    private readonly ILogger logger;

    public UserController(IUserRepository repository, ILogger logger) {
        this.repository = repository;
        this.logger = logger;
    }

    [HttpGet]
    public ActionResult Index(Guid id) {
        this.logger.Log("Index called.");
        IUser user = this.repository.GetById(id);
        return this.View(user);
    }
}

Here we can see the implementation of IUserRepository and ILogger get passed in the constructor and are then used in the Index method.

However what would the example be if we wanted to create a new user and call the user repository to save it? Creating a new instance of IUser from our controller becomes an issue as we don’t know what the implmentation of IUser is.

The incorrect implementation I usually see is someone adding a reference to the implementation and just creating a new instance of it. A bit like this:

public class UserController : Controller {
    [HttpPost]
    public ActionResult SaveUser(UserDetails newUserInfo) {

        IUser user = new User;
        user.FirstName = newUserInfo.FirstName;
        user.LastName = newUserInfo.LastName;
        this.repository.SaveUser(user);
        return this.View(user);
    }
}

This will work, but fundamentally defeats the point of using dependency injection as we now have a dependency on the user objects specific implementation.

The solution I use is to add a factory method to our User Repository which takes care of creating a User object.

public class UserRepository : IUserRepository {
    public User CreateUser() {
        return new User();
    }
}

Responsibility of creating the object now remains with its implmentation and our controller no longer needs to have a reference to anything other than the interface.

public class UserController : Controller {
    [HttpPost]
    public ActionResult SaveUser(UserDetails newUserInfo) {

        IUser user = this.repository.CreateUser();
        user.FirstName = newUserInfo.FirstName;
        user.LastName = newUserInfo.LastName;
        this.repository.SaveUser(user);
        return this.View(user);
    }
}
Advertisements

Populating the internal search report in Sitecore

Out the box Sitecore ships with a number of reports pre-configured. Some of these will show data without you doing anything. e.g. The pages report will automatically start showing the top entry and exit pages as a page view is something Sitecore can track.

Other’s like the internal search report will just show a message of no data to display, which can be confusing/frustrating for your users. Particularly when they’ve just spent money on a license fee to get great analytics data only to see a blank report.

Internal Search Report

The reason it doesn’t show any information is relatively straight forward. Sitecore doesn’t know how your site search is going to work and therefore it can’t do the data capture part of the process. That part of the process however is actually quite simple to do.

Sitecore has a set of page events that can be registered in the analytics tracker. Some of these like Page Visited will be handled by Sitecore. In this instance the one we are interested in is Search and will we have to register it manually.

Search Event

To register the search event use some code like this (note, there is a constant that references the item id of the search event). The query parameter should be populated with the search term the user entered.

using Sitecore.Analytics;
using Sitecore.Analytics.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using SitecoreItemIds;

namespace SitecoreServices
{
    public class SiteSearch
    {
        public static void TrackSiteSearch(Item pageEventItem, string query)
        {
            Assert.ArgumentNotNull(pageEventItem, nameof(pageEventItem));
            Assert.IsNotNull(pageEventItem, $"Cannot find page event: {pageEventItem}");

            if (Tracker.IsActive)
            {
                var pageEventData = new PageEventData("Search", ContentItemIds.Search)
                {
                    ItemId = pageEventItem.ID.ToGuid(),
                    Data = query,
                    DataKey = query,
                    Text = query
                };
                var interaction = Tracker.Current.Session.Interaction;
                if (interaction != null)
                {
                    interaction.CurrentPage.Register(pageEventData);
                }
            }
        }
    }
}

Now after triggering the code to be called a few times, your internal search report should start to be populated like this.

Internal Search Report Populated

Optimize the Rich Text Editor in Sitecore

When it comes to building a Sitecore site your first thought probably isn’t that you are going to need to make any setting updates or customization’s to the rich text editor. After all when you learn about building a site its mostly focused around creating components to add and remove from pages, but there are a couple of things that will greatly enhance your content editors experience.

Configure the toolbars

Out the box Sitecore ships with 4 toolbar configurations. These are defined in the core db here:

  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Default
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Full
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text IDE
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Medium

The “Rich Text Default” toolbar

Default Toolbar

The “Rich Text Full” toolbar

Full Toolbar

The “Rich Text IDE” toolbar

IDE Toolbar

The “Rich Text Medium” toolbar

Medium Toolbar

As the name suggests, by default your content editors will see the default toolbar that contains a very limited number of options. This may in-fact be to limited and you need to offer the content editors one of the toolbar’s with more options. Equally, the full toolbar may give to many options such as font’s and you would want to offer a more restricted set of options.

Setting a toolbar on a field

You can set a toolbar on each individual field by specifying the path in the template fields source field. This is particularly useful when a field needs specific options, such as a text area that should allow a user to configure bold, italics and links but shouldn’t ever contain an image.

Setting toolbar in on an individual field

Updating the default toolbar for a rich text field

When you want to change the toolbar for all rich text fields, a better option is to update which toolbar is used by default. You can do this with a patch config file.


<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="HtmlEditor.DefaultProfile" value="/sitecore/system/Settings/Html Editor Profiles/Rich Text Full" />
    </settings>
  </sitecore>
</configuration>

Updating the rich text editor css

A second way of customizing the rich text editor that you should consider is to make changes to the css file that the editor uses. By default this will use a css file called default.css that you will find in the root of the site. You can see this being referenced form a config setting if you look at the showconfig.aspx page.

<!--  WEB SITE STYLESHEET
    CSS file for HTML content of Sitecore database.
    The file pointed to by WebStylesheet setting is automatically included in Html and Rich Text fields.
    By using it, you can make the content of HTML fields look the same as the actual Web Site
-->
<setting name="WebStylesheet" value="/default.css" />

You can change this to use a different css file using a patch config file as follows:


<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <settings>
      <setting name="WebStylesheet">
        <patch:attribute name="value">/rich-text-editor.css</patch:attribute>
      </setting>
    </settings>
  </sitecore>
</configuration>

Now you may be wondering why you would want to do this, after all Sitecore offers an experience editor mode that will show the entire webpage as it will appear to visitors and also offers inline editing. However some aspects of a page can be better achieved using css styles rather than new components or new fields and content editor will need both an easy was to apply these style and a visual way to see that they have been applied, irrespective of if they are using the experience editor or the content editor.

For example, in this section of a blog post from Scott Hanselman he has highlighted some text as an aside which can easily be achieved in a rich text editor by applying a css class.

Hanselman Blog Aside

The first step to enabling this in Sitecore is to make sure you’re using a toolbar that allows the user to select css classes (that’s any but the default).

Next by creating a stylesheet that just contains the relevant style to be applied, the content editor can now select this in the css drop down;

.aside {
    border-left: 2px solid #e2842c;
    background-color: #f7f7f7;
    padding: 5px;
    margin: 5px;
    display: block;
}

CSS drop down

The preview will now also give visual feedback indicating what this is going to look like. It doesn’t have to look exactly like the webpage will, just enough for the content editor to understand.

Rich Text Editor