« Posts under code snippets

Monitor your Sitecore server’s health

Having a website up and running reliably requires that you monitor its health. You should always be using a monitoring tool like Pingdom (there are many others). That way, you can get notified when the website is down.

Now, there are several ways of making sure that things are ok at runtime. For example:

  • Sitecore’s HeartBeat.aspx for Load Balancer Health Checks – Standard page in Sitecore that does some limited checks. It’s a good idea to monitor this page.
  • Sitecore Diagnostics Toolset – A desktop application that does various checks to see if your Sitecore implementation is correctly working, with regard to things like security, indexing, performance and scalability. It’s a smart idea to use this tool periodically, but it won’t be helpful for monitoring purposes.

Personally, I like to monitor more than just if a website is up. I also want to know if key parts of the system are functioning properly, like connections to other systems, if certain content is available and if my indexes are ok. These checks may be very specific to my implementation.

That’s why I created a simple drop-in .aspx script that you can easily configure to check these things. You can find it in this Gist on Github. Example output:

It’s quite easy to configure and extend. Just read through the implementation of the Page_Load(…) method. Some more details here:

Security

You’ll want to limit who gets to use the monitoring page, to prevent abuse and prevent hackers from getting details about your implementation. This is especially important if the checks you are doing may impact system performance significantly. Make sure your monitoring tool’s requests to the page match your security settings here.

 

Adding checks

You can add checks to do when the page is requested by adding them to the ChecksRun collection. Some examples are in the code below. They include checking specific items’ presence in databases and having versions and layout/presentation. They also include checking if search indexes contain enough items, if certain url’s are reachable from the server and if configuration is specified correctly.

It’s also easy to implement your own specific types of checks. Add them to the region “actual checks” as classes that implement the ISitecoreCheck interface (or use the SitecoreCheckBase class).

 

Tags

You may not always want to run the same checks. Perhaps some checks should only be performed at night and some checks may be specific to your DTAP or CM/CD servers specifically. You can use tags to limit which tests are run, as demonstrated in the example below. And then you can specify which tags are applicable by specifiying them |-separated in the url parameter “tags”. The url //SitecoreChecks.aspx?tags=fail would result in the following:


 

Let me know if you have any questions/suggestions.

Validating your code references to serialized data

Sitecore developers often need to reference content items from their code. E.g.: a template or branch ID for an import function or reading a global setting that’s stored in the content tree. Using IDs is usually preferred over using paths, because paths may change. It’s considered good practice to keep those ID references in a class with constants, like this:

After recently contributing some serialization logic to Sitecore.FakeDb, I got the idea to write unit tests that validate if these constants have values that are actually in Sitecore. We can use TDS or Unicorn serialized data to validate this.

The following unit test does just that (uses NUnit, FluentAssertions, Sitecore.FakeDb and Sitecore.FakeDb.Serialization):

Just pass in the types (that have Sitecore IDs as static properties) using the “Values” attribute.

But I didn’t stop there. At my company, we’re currently working on a project that uses Glass Mapper. Glass Mapper can use attributes to link mapped classes to the correct Sitecore templates. And in a similar way, properties can be linked to field IDs.

I wanted to validate all those IDs as well, and also check if the field IDs are on the right templates.

That’s why I wrote the following unit test. It finds all the types that have attributes like this and deserializes the corresponding templates. It also checks if the fields are there.

To use it, you need to pass in one type from the assembly that you want to test (or multiple) using the “Values” attribute.

Since I’m quite new to using Glass Mapper, I’d be interested to get some feedback on this. I’m pretty sure there’s more that can be tested.

Bye!

Unit testing with test fixtures presentation slides and demo project

Recently, I gave a presentation for the Dutch Sitecore user group (SUGNL) about unit testing with test fixtures. I’ve blogged about this subject before (the initial post can be found here).

You can download the slides in both Dutch and English:

The demo project that I used, also containing the code for my post about using item wrappers as models in Sitecore MVC is also available as a download.

Hopefully, these downloads can be useful and please let me know if you have any questions or other feedback!

Use item wrappers as models in Sitecore MVC

I’ve been experimenting with Sitecore 6.6 MVC lately. I love the very clean Razor views. And if you’re used to working with a rich domain model that wraps your Sitecore items, then you’ll hardly ever need a controller rendering (because your view-logic will be on your model). Most of the layouts and sublayouts will be view renderings.

Now, when developing in ASP.NET Web forms, I will usually have a base class for my controls that has a generic type parameter that reflects what type of item it will take as a datasource. This way, I can easily access the right fields in a strong-typed fashion. And I wanted this same setup in MVC.

So, after completing the steps in this blog post, you will be able to make a Razor view like this:

Line-by-line explanation:

  1. Declare the model to be a IRenderingModel-derived type (this way, it will be initialized in the same way as the default rendering model). The generic type parameter shows that this particular view will take any item that has the “Page”-template or a template that inherits from it as its datasource.
  2. Use an extension to the SitecoreHelper to reference the “Title” field. It uses a lambda expression, so that the helper method can ensure that the “renderField” pipeline is run; this ensures that among other things, the page-editor support will be preserved.
  3. The same as #2, but for the “Text content” field.

Side-note: I use my own CompiledDomainModel module (CDM) to generate wrapper classes based on Sitecore templates. So the following example code will use it as well. But you can probably easily adapt the following code to work with your mapping/wrapping framework. The code is from a project that I will soon use in a presentation for the SUGNL (hence, the UnitTestingDemo namespace).

The following code is for the RenderingModel. It allows access to the datasource itemwrapper in the type you want. Notice that the “out” keyword is used before the generic type parameter declaration. This means that the type is covariant, so that you can use a base type in your model declaration at the top of the Razor view (e.g. IRenderingModel<PageBase> instead of IRenderingModel<Page>).

To create the RenderingModel, we need to plug the following in to the “mvc.GetModel” pipeline.

Hook this code up to the “mvc.GetModel” pipeline using the following configuration (use a config file in the “/App_Config/Include” folder to make a nice patch of this):

Now, when you make a rendering, be sure to add “typedmodel=1″ to the parameters field in Sitecore for that rendering. That way, the “mvc.GetModel” pipeline will know when to create a typed model.

And you’re all set to use the typed model in your Razor views. But there’s one thing left; the lambda syntax support. This works in the same way as the CdmFieldRenderer control from a previous blog post. You can use the following helper class:

To be able to use this extension without having to import it every time, you can add it to the “/Views/Web.config” file, like this:

I know it takes a little time to setup, but it makes your Razor views very clean and you’ll have code-completion for your field names. If you want, you can compile your Razor views at build-time by editing your MVC project file and setting “<MvcBuildViews>true</MvcBuildViews>”.

Next week, I’ll be doing a presentation on unit testing with test fixtures and I’ll also get into unit testing the Razor view that I mentioned here. The whole project and the slides will be available for download on this blog afterwards.

Sitecore unit testing with test fixtures – media library support added

I recently wrote a post on Sitecore unit testing with test fixtures. I’ve now added support for the media library (updated in the project on GitHub).

So now, you can also unit test code that imports an image into the media library.

And here’s some code to check if it works correctly.

T-SQL pocket knife code

Sometimes I like to dive into the SQL databases that hold all of our precious Sitecore content and go wild. No really; sometimes the Sitecore tree, XPath builder or search function are just not the easiest tools to research a particular problem. Once you understand the database schema of Sitecore (which is not that difficult), querying the databases directly can be of great help.

Here is a script that creates 2 handy functions that you can use to make querying Sitecore data just a little easier:

After running this script (be sure to change the statement in line 1 to match your database name), you can write queries such as this one:

This results in:

Screenshot of the result of the previous query

Since the SC_GetPath function uses recursion, make sure your query does not go out of control. SQL Server does not allow too many recursions by default.

Bypass the content API for better performance

The Sitecore content API provides a very easy way of accessing your content. It is highly optimized for performance with internal caching. You can find a great overview of the different query strategies here.

But in some specific cases, the API will not provide you with the right tools to get what you want, with the performance that you want. In those cases you have 2 options:

  1. Persist a more suitable representation of your data. E.g.: output caching, Sitecore caching, Lucene indexing.
  2. Strip some overhead, so functionality that is not needed at that point can be skipped. An example will follow.

Both of these methods have their drawbacks, so it is important to evaluate them when choosing a solution. Some drawbacks for the first method:

  1. More storage/memory is needed.
  2. The data representation must be kept consistent with the original data (can result in bugs that are hard to spot if implemented incorrectly).

Drawbacks of the second method:

  1. Relies on the underlying implementation. You may have to change the implementation with future upgrades.
  2. If the stripped functionality turns out to be needed in the future, the implementation may become unsuitable.

An example of the second method

If we want to get the descendant nodes of a certain item, we can easily use the content API:

But if we want to limit the descendants to items with a certain template, this is a better method:

However, in this case, we will not get items with template ‘Jpeg’ or ‘Pdf’. Those templates inherit from the ‘File’ template. So if we want to get all descendants that inherit from the ‘File’ template, we need a helper method:

You could make this into an extension method if you want. Here’s how we can use this method to get all the descendants that inherit from ‘File’:

This will be quite slow if there are many descendants. We will bypass the content API and query the SQL server database directly to make it much faster.

Place the query in a stored procedure if you want to use this method in production. For reference, here is a different article which discusses bypassing the content API.

Measuring speed

In my opinion, any performance improvement (especially if it has significant drawbacks) must be proven to be worth it! So I’ve measured the speed of this method and a simpler one against the normal Sitecore way of doing things. Here’s the result:

As you can see, the performance gain can be significant. So if the drawbacks are acceptable, this may be a good option. Here is the aspx so you can test it for yourself:

Design Structure Matrix (DSM) for your content tree

A design structure matrix (or dependency structure matrix) can help you to analyze the dependencies of your system and spot potential problems. This is especially useful when analyzing code, like you can do with the .NET Reflector Add-In you can find here.

Since certain aspects of your system structure can also be derived from the Sitecore content tree, I thought it might be useful to make a DSM for that. The aspx at the end of this post can be used to analyze the dependencies in your content tree!

An example of how this can be useful:

Let’s say you have a multisite Sitecore environment that currently has 3 websites (A, B and C). Some parts of the websites are quite similar and developers have copied different items between the websites. Website B is (functionally) essentially a subsite of site A. You could say that website B ‘depends’ on website A. And actually, since website A will have a link to site B, website A also depends on website B. Website C should be completely independent.

Now, I have opened the DSM aspx. After selecting the master database, expanding all the relevant nodes and selecting the websites, I am now ready to create a DSM. After clicking the “Update DSM data” button, I can see the following:

From this matrix, I can see the following (start reading by choosing a row and then choose the cell; the numbers in the top row reference the items in the column on the left):

- Website A (or one of its descendants) has 1 link to website B (or one of its descendants).
- Website B (or one of its descendants) has 3 link to website A (or one of its descendants).
- Website C (or one of its descendants) has 1 link to website B (or one of its descendants).

That last one could be a problem! Website C should have no links to the other websites. This probably happened because I copied something from website B to website C and I forgot to change the link.

To see where the problem is exactly, I click on the table cell (coordinate: 1.3 Website C, 1.2). The information in the next image is displayed:

The menu configuration for website C references a page in website B, instead of a page in website C. After I correct this error, I click “Update DSM data” again. Now the matrix looks like this:

That’s better; Only websites A and B now have references to each other.

If I need a more detailed look, I can select anything that I think is relevant in the tree. So the aspx page could look like this:

You have to get used to reading this type of matrix, but it can be a very useful tool. This example is obviously quite simple; more complex situations may be found in the “real world”.

The tool is not exclusively for solving problems. It can also be helpful for quickly understanding how a system is setup.

Just copy the following code to an aspx file and you’re ready to use the tool:

Better FieldRenderer usage with CDM

We’ve been using CompiledDomainModel for several projects now. And we keep inventing new ways to make things even better.

Yesterday I was brainstorming with some colleagues about a better way of using the Sitecore FieldRenderer in combination with CDM. I found a very neat new way of doing this. But I’d like to share some of the different options, so that you can choose the best one for you.

Traditional FieldRenderer without CDM:

  • Simple implementation
  • Spelling errors result in not displaying anything instead of an error
  • Not wrapped, so no custom functionality can be placed on the item

Use CDM without FieldRenderer:

  • Easy implementation
  • Typed access
  • The rendering pipeline is not used, so the page editor will not make this output editable

Traditional FieldRenderer with CDM (currently the most used with CDM):

  • A bit of a pain to unwrap the Sitecore item every time
  • Spelling errors result in compilation errors, which is great!
  • The FieldName can refer to a field from an entirely different type (though this is not a very common mistake)

Custom FieldRenderer with CDM:

  • The same as the previous one, but without the need to unwrap the Sitecore item every time
  • You need to use a non-standard control

Custom FieldRenderer with CDM and lambda expression:

  • The best possible type-safety
  • Only usable in .NET 4
  • You need to use a non-standard control

The last one is the nicest one in my opinion. You can use it as if you are not using a field renderer at all, and still get all the benefits of a fieldrenderer (use of the rendering pipeline and editable in the page editor).

It works by using the expression tree of the passed-in lambda expression and reflection to determine the name of the field. It shouldn’t be too hard to create similar controls for sc:Link and sc:Image. Here’s the code:

Good luck!

Prevent nullrefs when databinding with placeholders

I love databinding. It allows me to keep view-logic in ascx/aspx files so I don’t have to read long code-behind files laden with initialization logic and page lifecycle related crap.

Databinding works better with WPF and Silverlight than it does with ASP.NET. But in my humble opinion it still beats the alternative in ASP.NET.

One very annoying problem I’ve run into when using databinding in ASP.NET is the use of placeholders. The placeholder is a control that we use as the equivalent of an if-statement in C#. If the “Visible” property evaluates as true, only then the contents are rendered.

This works well in most cases. But when you use databinding it sort of breaks. For example:

This code will work perfectly fine, unless “SomeProperty” evaluates to null, because the contents of the placeholder are always evaluated! This problem is especially annoying with Sitecore FieldRenderers, which don’t allow the “Item” property to be null. A simple fix to this problem is to repeat the null-check within the placeholder, like so:

But if you would have a more complicated condition, many unsafe binding statements within the placeholder or nesting of several placeholders, this fix can prove to be quite cumbersome.

So I tried to find a good workaround for this problem and I observed the repeater control. It does not have this problem, because the contents of “ItemTemplate” will never be evaluated if the collection in the datasource is empty. This is what I came up with:

That works really well! I used the repeater as a placeholder and now, if “SomeProperty” evaluates to null, there will be no problem; the contents of “ItemTemplate” are never evaluated by the databinder.

Still, this is quite an ugly workaround, because it’s pretty verbose and not really intuitive to programmers. So we need a better solution.

And I found one! I created a custom control that derives from the PlaceHolder control. The only difference in behaviour is that the contents of the control are not evaluated by the databinder if the “Visible” property is null. Here’s the code for the control:

This is a pretty simple change, but it makes life so much easier. If we import the control and use it in the following way, we no longer have to worry about nullref problems:

Happy coding!

UA-4216957-1