Excluding an item/page from search or index

This is a generic situation most of Sitecore geeks face during their development work. Though, you may find several solutions over the internet, but what I am going to put here is the most simple and robust solution.

Just a checkbox and few lines of code and you are done. Let’s do it now.

  1. add a checkbox field on the item template or on the base template ( your choice) , name it something meaningful like “ExcludeFromSearch” or “DoNotIndex”
  2. Create a custom item crawler. see the code below
    using Sitecore.ContentSearch;
    using Sitecore.Data;
    using Sitecore.Data.Items;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    namespace Learning.Framework.Search.Indexing.Crawler
    {
    public class CustomItemCrawler : SitecoreItemCrawler
    {
    protected override bool IsExcludedFromIndex(SitecoreIndexableItem
    indexable, bool checkLocation = false)
    {
    var isExcluded = base.IsExcludedFromIndex(indexable, checkLocation);
    if (isExcluded)
    return true;
    Item item = indexable;return (item[new ID(pass the checkbox field id here)] == "1") ? true: false;
    }
    protected override bool IndexUpdateNeedDelete(SitecoreIndexableItem
    indexable)
    {
    var needDelete = base.IndexUpdateNeedDelete(indexable);
    if (needDelete)
    return true;
    Item item = indexable;
    return (item[new ID(pass the checkbox field id here)] == "1") ? true:
    false;
    }
    }
    }
  3. Patch the above custom crawler to the config as shown belowExcludeFromSearch-config
  4. Build the solution and publish to the server. Check the checkbox on whichever item you want to exclude/remove from search.
  5. Once publish is done, rebuild the target index from control panel and you are done.

Note: There is a method in the above CustomItemCrawler , the method name is IndexUpdateNeedDelete

this is to delete the existing items/pages from the index.

I hope this post will help some of you.

Happy Coding !!!

How to use Google reCaptcha on WFFM with ASP.NET Layout

Recently I needed to have reCaptcha on my forms so that I can secure them from bots. My client specifically wants to use reCaptcha so that we can have “I’m not a robot” check on our web forms.

Imnotrobot.png

There is a guide provided by Sitecore on “How to use reCaptcha on forms”, but that is for MVC layouts (See that guide here), not for ASP.NET layouts. I have spent a lot on finding a way to use reCaptcha on ASP.NET layout and then I landed on here . but, the question was, how to use this for WFFM as we don’t have access to the code. So I thought of implementing this by creating a custom field type for WFFM and render that HTML and javascript via that new field type.

So let’s take a look at that implementation.

  1. Create a class and inherit it from Sitecore.Form.Web.UI.Controls.LabelreCaptcha-code
  2. use the below Javascript code for the button click event
    $(".scfSubmitButton").click(function() {
    /*read the tocken generated by reCaptcha , token will be generated only
    if the validation is successfull */   
        var rcres = grecaptcha.getResponse();
        if (rcres.length) {
            return true;
        } else {
            return false;
        }
    });
    
  3. Create a custom field type in Sitecore at this location – /Sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types/Custom  custom-field-type.png
  4. Download the recaptcha-dotnet-1.0.5.0-binary.zip and place the Recaptcha.dll into your website’s bin folder.
  5. Now the new custom field type is ready. You just need to add a field on your form and select the field type as your new custom field (reCaptcha in my case). field-on-form.png

Publish your form and see the reCaptcha in action as shown in this screenshot.actual-use.png

I know not many people are using Sitecore on ASP.NET layouts, MVC is lightweight and far good for Sitecore. But there are some implementations on ASP.NET layouts as well, so Wrote this post in a hope that it will help someone like me.

Understanding the Rendering Parameters

Being a Sitecore developer, you must have heard a term called “Rendering Parameters”. In today’s post we’ll together explore the Rendering Parameters with WWH (What, When & how) scenarios.

What is Rendering Parameter?

When to use Rendering Parameters?

How to use Rendering Parameters?

So I’ll keep this post as simple as possible and will explain you the concept of Rendering Parameters.

What is Rendering Parameter?

Rendering Parameter is a way to pass the additional item(s) to the rendering or component apart from rendering data source.

When to use Rendering Parameters?

Let’s assume, you are in a situation where content editors need to use some additional items on a component apart from its actual data source. For example – I am going to use Rendering parameter to pass an additional CSS class to the component, which will allow my content editors to choose the style of their component.

How to use Rendering Parameters?

Let’s jump to the exercise to understand the complete scenario and see how we can make use of Rendering Parameter.

This complete exercise is divided into 3 easy tasks. Which I’ll be explaining you one by one.

Task-1 Creating a Parameter Template

Create a new template and make sure this template inherits from a base template of standard Rendering Parameters – “/System/Layout/Rendering Parameters/Standard Rendering Parameters”

RP-1

And create the fields as per your requirement. In my scenario – I just need a single text field. See the below image.

RP-2

Task -2  Reference you parameter template

Reference you parameter template on your required rendering under the Editor Options section of your rendering, as shown below

RP-3

Once you reference your parameter template to your rendering, you can then check the same by going to the content item where you are using this rendering and go to the Presentation > Details > Final Layout and select your rendering and click edit – you should see your Rendering Parameter field there. See the image below

RP-4

You can notice here that your complete template field(s) and section are available here and Content Editors can make use of this to pass some additional data to the component or rendering.

Task -3 Read the parameter value in code

In my scenario, I am using MVC and used a controller rendering to make it work. So I’ll show the code to access the parameter value in MVC controller action.

 public ActionResult Index()
        {

            var item = Sitecore.Context.Item;
            var addtionalCssParameter = RenderingContext.Current.Rendering.Parameters["Background Class"];

            var model = new StandardPage
            {
                Title = item.Fields["Title"].Value,
                Description = item.Fields["Description"].Value,
                AdditionalCss = addtionalCssParameter
            };
            return View(model);
        }

Well, if you are using ASP.NET instead of MVC then I assume you must be using the Sublayout as renderings and that should not be a show stopper for you. You can still use the rendering parameters in the same way we use for MVC controller renderings. The Only task which is going to be a bit different is –  reading the parameter value in code.

So nothing to worry, here is the code to read the rendering parameter value from .ascx.cs file.

public string AdditionalCss
        {
            get
            {
                var sublayout = ((Sublayout) this.Parent);
                NameValueCollection renderingParameter = Sitecore.Web.WebUtil.ParseUrlParameters(sublayout.Parameters);
                return renderingParameter["background Class"];
            }
        }

And that’s all about the Rendering Parameters.
I hope this post will help you in your further Sitecore journey. Happy Coding 🙂

Creating a Custom Field Validator

While working on some of my previous Sitecore projects, I had to create some custom field validators. Most of the time, the Sitecore beginners are stuck with such tasks, So I thought of writing it down here to help them in creating their first ever custom field validator. So we are going to use a validator that we create to validate the End Date.

  • Creating the custom validator and inherit it from StandardValidator
using System;
using System.Runtime.Serialization;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Data.Validators; 

namespace SitecoreTricks.Utils.Helpers
{

[Serializable]
class EndDateValidator: StandardValidator
{

public EndDateValidator()
{}

public EndDateValidator(SerializationInfo info, StreamingContext context) : base(info, context) { }

protected override ValidatorResult Evaluate()
{
Item item = base.GetItem();
DateField start = item.Fields["Start Date"];
DateField end = item.Fields["End Date"];
if (start.DateTime <= end.DateTime) return ValidatorResult.Valid; this.Text = $"The End Date ({end.DateTime}) should be equal to or greater than the Start Date ({start.DateTime})"; return ValidatorResult.CriticalError; } protected override ValidatorResult GetMaxValidatorResult() { return GetFailedResult(ValidatorResult.CriticalError); } public override string Name => "End Date Validator";
}
}

Note – We used the Serializable attribute and created a constructor as well to make sure that our custom validator works fine with validator button. If we don’t use Serializable attribute and constructor, the Validator button would throw an exception.

  • Creating the custom Validation Rule in Sitecore

To get the custom date validator on work, we need to have a validation rule item defined in Sitecore (/sitecore/system/Settings/Validation Rules/Field Rules).

Validator1

Note – Remember to use your namespace and class under the “Type” field.  Also, provide the Title and Description.

  • Now apply the validation rule on your field.

Go to your template and navigate to the field. Scroll down the content window and expand the “Validation Rule” section and that’s the place where you are going to use your custom field validator.

Here you will see four fields where you can use the validator. These four fields are as below

  1. Quick Action Bar – This will show you the validation error on bar left of the content tree.
  2. Validation Button – This will run the validation by clicking of the Validation button in review tab.
  3. Validation Bar – This will show you the validation result in bar right to the content editor.
  4. Workflow – this runs the Validation of workflow actions.

Below are the above four fields where I have selected my custom End Date Validator

Validator-2

  • Now see the magic of your custom validator.

Create an item of the type of your template (in my case it is Event details) and the play with the End Date value and you will see the validation result on all the places where you have selected your validator in above image.

Validation Result for choosing the End Date Validator on Quick Action Bar will display as below

Validator-result1

Validation Result for choosing the End Date Validator on Validation Button will display as below

Validator-result3

Validation Result for choosing the End Date Validator on Validation Bar will display as below

Validator-result2

So that’s how you are going to use your custom validator. But there are few more things to keep in mind which are as below.

From our custom class, we are returning the “Critical Error” as result of validation failure, but there is some more result which can be returned here depending on the requirement.

  1. Suggestion
  2. Valid
  3. Warning
  4. CriticalError
  5. Error
  6. FatelError
  7. Unknown

ResultType

That’s it. Now help your content editors by implementing the existing as well as by creating the custom validators.

 

Sitecore 9 on Windows 8.1, my experience

XtremDev - Sebastian Tecsi | Sitecore Blog

There are a couple of articles about Sitecore 9 on a Windows 8.1 development machine, and since it’s bit out of hand for me to upgrade to Windows 10 I’ve decided to take the bull by the horns and finally do it. Even that I’ve lost a bet with @SitecoreClimber that will manage to install Sitecore 9 to my Windows 8.1 in fist-second week of the launch without any troubles.

Windows 8.1 does not have Powershell 5.1 as its needed by SIF, so you can install it from here, as Windows Management Framework 5.1 includes also Powershell 5.1. An alternative way it to use this command choco install powershell if you are using Chocolatey.

After a restart of the machine it’s time to install Sitecore Install Framework and Sitecore Fundamentals. So in a Windows Powershell opened as Administrator execute this:

Register-PSRepository -Name SitecoreGallery -SourceLocation https://sitecore.myget.org/F/sc-powershell/api/v2 Install-Module SitecoreInstallFramework…

View original post 411 more words