Sitecore Explorations

XConnect: Certificate was not found

Experience Analytics was not working on Production environment. I checked the logs and it was throwing Certificate was not found error. 

Exception: System.InvalidOperationExceptionMessage: The certificate was not found.Source: Sitecore.Xdb.Common.Webat Sitecore.Xdb.Common.Web.CertificateWebRequestHandlerModifier.Process(HttpClientHandler handler)at Sitecore.Xdb.Common.Web.CommonWebApiClient`1.CreateRequestHandler()at Sitecore.Xdb.Common.Web.CommonWebApiClient`1.CreateClient()at System.Lazy`1.CreateValue()at System.Lazy`1.LazyInitValue()at Sitecore.Xdb.Common.Web.CommonWebApiClient`1.<ExecuteAsync>d__37.MoveNext()--- End of stack trace from previous location where exception was thrown ---at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)at Sitecore.Xdb.Common.Web.CommonWebApiClient`1.<ExecuteGetAsync>d__32.MoveNext()--- End of stack trace from previous location where exception was thrown ---at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)at Sitecore.XConnect.Client.WebApi.ConfigurationWebApiClient.<Refresh>d__4.MoveNext()
  • My first guess was certificate would have expired, but it was valid. 

  • Second guess was thumbprint could be wrong, but thumbprint was perfectly matching with the config value(\App_Config\AppSettings.config file , in the validateCertificateThumbprint setting).

  • Started wondering why it can’t find the certificate for some reason?  Came to know that need to add an application setting to the web app called WEBSITE_LOAD_CERTIFICATES and the value needs to be the certificate thumbprint.

  • This application setting is required for the app service to load the certificate into the local certificate store of the host running the app service. 

Once the setting is added and I no longer see the error in logs and the Experience Analytics started showing some number/graphs. Yay!

Hope this helps. Any questions, please leave a comment.

Happy Sitecoring.

0

Sitecore 9 Forms: Uncaught TypeError: Cannot read property ‘unobtrusive’ of undefined

Are you getting this error on Sitecore 9 Forms Submission? I got it and it took me some time to figure out. It’s all related to Validation. Here are the points to check to narrow down the issue —

  • If you have form fields set it to mandatory, change it to optional and see if that makes the submission successful. If so, one of the field validation is causing trouble.

  • It happens for custom form control quite often, where you need add the validation to razor view file and make sure you have this attribute – GenerateUnobtrusiveValidationAttributes.
<label for="@Html.IdFor(m => Model.Value)" class="@Model.LabelCssClass">@Html.DisplayTextFor(t => Model.Title)</label>
<select data-trigger class="@Model.CssClass @Model.Name" name="@Html.NameFor(m => Model.Value)" id="@Html.IdFor(m => Model.Value)" data-sc-tracking="@Model.IsTrackingEnabled" data-sc-field-name="@Model.Name" @Html.GenerateUnobtrusiveValidationAttributes(m => m.Value)>
</select>
@Html.ValidationMessageFor(m => Model.Value)
  • Compare your custom control razor file to any one of inbuilt form controls ([iis-site-folder]\Views\FormBuilder\FieldTemplates ) like below and if you see any difference on attributes, add it out.
  • Finally a simple check: make sure to publish all the forms and view the landing page in live mode(not in preview mode)

Hope this helps. Happy sitecoring.

0

Sitecore 9 Forms: Custom Grouped dropdown

I came across a requirement from a client that they wanted to show Country and it’s states grouped in a dropownlist. I created a custom grouped dropdown to fit into the scenario. Since this is an extension of dropdownlist, no speak knowledge required. 

Let’s get started

Step 1: Create custom dropdown list

Create a custom dropdownlist under
/sitecore/system/Settings/Forms/Field Types/Lists based on Field Type(/sitecore/templates/System/Forms/Field Type) template like below

Step 2: Create a code behind class and razor view

create a code behind class like this in VS project

using System.Collections.Generic;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Mvc.Models.Fields;

namespace Sitecore.Project.Example.Views.StateDropdown
{
	public class StateDropdown : DropDownListViewModel
	{
		protected override void InitItemProperties(Item item)
		{
			Assert.ArgumentNotNull(item, nameof(item));
			base.InitItemProperties(item);
		}

		protected override void UpdateItemFields(Item item)
		{
			Assert.ArgumentNotNull(item, nameof(item));
			base.UpdateItemFields(item);
		}

		public Dictionary<string, Dictionary<string, string>> Regions()
		{
			if(string.IsNullOrEmpty(DataSource)) return new Dictionary<string, Dictionary<string, string>>();
			Dictionary<string, Dictionary<string, string>> counrtyCollection = new Dictionary<string, Dictionary<string, string>>();
			Item item = Context.Database.GetItem(DataSource);
			var children = item.GetChildren();
			foreach (Item child in children)
			{
				counrtyCollection.Add(child.Fields["Name"].Value, new Dictionary<string, string>());
				foreach (Item desc in child.Children)
				{
					counrtyCollection[child.Fields["Name"].Value].Add(desc.Fields["Name"].Value, desc.Fields["Code"].Value);
				}
			}
			return counrtyCollection;
		} 
	}
}

Create a razor view like this and build project

@using Sitecore.ExperienceForms.Mvc.Html
@model Sitecore.Project.Example.Views.StateDropdown.StateDropdown
@{
	var regions = Model.Regions();
}
<label for="@Html.IdFor(m => Model.Value)" class="@Model.LabelCssClass">@Html.DisplayTextFor(t => Model.Title)</label>
<select id="@Html.IdFor(m => Model.Value)" data-trigger name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass" placeholder="Select Your Work Location" data-sc-tracking="@Model.IsTrackingEnabled" data-sc-field-name="@Model.Name" @Html.GenerateUnobtrusiveValidationAttributes(m => m.Value)>
	<option placeholder>Select Your Work Location</option>
	@foreach (var region in regions)
	{
		<optGroup data-id="@region.Value" label="@region.Key">
			@foreach (var state in region.Value)
			{
				<option value="@state.Value">@state.Key</option>
			}
		</optGroup>
	}
</select>
@Html.ValidationMessageFor(m => Model.Value)

Step 3: Fill out the fields

Fill out the View Path, Model Type and Property Editor(should be Property Editor Settings/DropDown List).  

you are now all set to utilize the custom dropdown list in Forms Designer. Don’t forget to publish the field!

Hope this is helpful. Any questions, please leave a comment.

Happy Sitecoring.

0

Sitecore 9 Forms: Custom Regex Validation

I came across a scenario where i implemented a custom validation on Sitecore 9 Forms. Sharing my knowledge here. You can achieve this in three simple steps.

Step 1: Create custom validator

Create a custom validator under
/sitecore/system/settings/forms/validation based on Validation(sitecore/templates/System/Forms/Validation) template like below

Step 2: Fill out the fields

Fill out your own regex and error message. You can copy the Type value from other validator.

Step 3: Assign the custom validator

You can now add the new custom validator to any Form fields(
/sitecore/system/Settings/Forms/Field Types). All set and no code required!

Hope you found this blog helpful. Any questions, please leave a comment.

Happy Sitecoring!

0

Sitecore 9 Forms: Save Data

Are you developing Sitecore 9 Forms and wondering where does the data get saved on Save Data?

  • It goes to local DB called Experience Forms (The DB comes with it as part of Sitecore 9 installation OOTB)
  • It has two tables – dbo.FormEntry and dbo.FieldData holds all the information.
  • The below first query gives the top 1000 form submissions. From the form ID, you can query against dbo.FieldData for any specific field values.

SELECT TOP (1000) [ID]
,[FormItemID]
,[Created]
FROM [sc91local_ExperienceForms].[dbo].[FormEntry]


SELECT TOP (1000) [ID]
,[FormEntryID]
,[FieldItemID]
,[FieldName]
,[Value]
,[ValueType]
FROM [sc91local_ExperienceForms].[dbo].[FieldData]

You can also export the data from ‘Export the data to CSV‘ button from Form Designer.

Hope this information is helpful. Any questions, please leave a comment.

Happy Sitecoring.

0

Sitecore 9.1 Forms: Conditional Logic

Conditional Logic is great new feature introduced in Sitecore 9.1 Forms. Basically you can add conditions to show/hide fields based on user input.

In this example below I set up a drop down and couple of sections that show/hide the section(you can go fields as well) based on user interaction.

My simple conditional logic form

Now I added the conditions to drop-down list by clicking on the Conditions section in the form elements pane.

Edit conditions to add new condition logic

Now are you wondering why the condition logic looks weird? Here is how it works –

  • All Condition are evaluated and applied in sequence.
  • Foreach condition, if the Condition matches, then apply selected action. Else, apply inverse of selected action.

Added the form to a web page and here is how my output looks –

When I chose 1, showed the Attendee #1 section
When I chose 2, showed both Attendees section

1. Dropdown Selection: Empty

  • Condition 1 Evaluation = False. Inverse selected action (Hide section1 and section2)
  • Condition 2 Evaluation = True. Apply selected action (Hide section1)

Results: Hide both section1 and section2

2. Dropdown Selection: 1

  • Condition 1 Evaluation = False. Inverse selected action (Hide section1 and section2)
  • Condition 2 Evaluation = False. Inverse selected action (Show section1)

Results: Show section1 and hide section2

3. Dropdown Selection: 2

  • Condition 1 Evaluation = True. Apply selected action (Show section1 and section2)
  • Condition 2 Evaluation = False. Inverse selected action (Show section1)

Results: Show both section1 and section2

Now you have the cool working conditional logic on the form. Any questions, please leave a comment.

Happy sitecoring!

2

Sitecore license file expired?

I have Sitecore 9.1 instance and today my sitecore license file expired. I had to replace the license.xml in multiple places to make sure my site, xConnect and Identity Server sites work.

  • Sitecore site:
    • The /App_Data folder
  • xConnect site:
    • /App_Data
    • /App_Data/jobs/continuous/AutomationEngine/App_Data
    • /App_Data/jobs/continuous/IndexWorker/App_Data
    • /App_Data/jobs/continuous/ProcessingEngine/App_Data (new to Sitecore 9.1)

Hope this helps if you have license expiration message.

Happy Sitecoring!

0

Sitecore 9 Forms: The required anti-forgery cookie __requestVerificationToken is not present

Have you submitted a form and it returned with this error ‘The required anti-forgery cookie “__requestVerificationToken” is not present’? If so, here is the resolution.

  • This could be because of caching. Can you check if your rendering component or container/page level caching check box is checked? if so, unchecking the caching will fix the issue.
  • Also here is quick check you can do to see whether your form is cached – Inspect the form and check the _requestverificationtoken value like below and refresh the page – do you see same value now? if so, your form is in cache!
 <input name="__RequestVerificationToken" type="hidden" value="O0P3KYBqgEZXlksWnY3fhu0PptEB0a47rRGMgHNnF6lIL2S8tcts9z9NxdxIum7ANKMv95FZB275AeLTw6WxcOl4jCQ1">  

2

Install Sitecore 9.1 quickly in 5 easy steps

Image result for install software

I’m participating in Sitecore Hackathon for the first time this year. One of the requirement is to have sitecore 9.1(Initial version) installed on your machine. So I want to share my experience how i quickly installed Sitecore 9.1 using SIF on developer machine in 5 easy steps. This post includes the prerequisites, preparation and installation.

Prerequisites:

  • OS: Windows 10, Windows Server 2016
  • DB:
    • Microsoft SQL Server 2017 or 2016 SP2 – Supports the XM database and is the required for the xDB
    • Microsoft SQL Server 2014 Sp2 – Only supports XM databases and does not support the xDB
    • MongoDB Server 3.6.6 – This is required if you are going to use MongoDB for the Collection database or as a Session State Provider
  • IIS 10
  • . NET
    • Sitecore XP 9.1.0 requires .NET Framework 4.7.1
    • Sitecore Identity server requires .NET Core Runtime 2.1.3
    • You must apply any available updates to the .NET Framework on every Sitecore installation
  • Search Indexing
    • Solr 7.2.1 – Default search provider
    • Azure Search – supported and recommended for Azure Cloud PaaS deployments only
    • Lucene – Only supports content search and does not support xConnect.
  • Powershell 5.1 – for Installing SIF

Preparation:

  • Download installation package(XP Single) from here
  • Extract the zip file you just downloaded
  • Again extract this file – XP0 Configuration files 9.1.0 rev. 001564.zip
  • Copy your license.xml file (If you have enrolled for Hackathon, you should have received the file in email)

Now let’s begin the installation!

Step 1: Solr 7.2.1 Install

Check out Jeremy Davis’s low effort Solr installs. It’s pretty cool! https://jermdavis.wordpress.com/2017/10/30/low-effort-solr-installs/

If you want to take traditional approach(Install as service using NSSM tool), here are the steps

  • Download from here
  • Install as service using NSSM tool

It opens the NSSM Service Installer like below. Fill out the fields.

  • Note: If you already another version of solr running, make sure to give different port name.
Solr 5 running as a service on Microsoft Windows

Step 2: Install SIF

Run the following scripts

Register-PSRepository -Name SitecoreGallery -SourceLocation https://sitecore.myget.org/F/sc-powershell/api/v2;
Install-Module SitecoreInstallFramework;
Install-Module SitecoreFundamentals;
Update-Module SitecoreInstallFramework;
Update-Module SitecoreFundamentals;
Import-Module SitecoreFundamentals -Force;
Import-Module SitecoreInstallFramework -Force;

Step 3: Update config files

Update the following files in the folder with the exact information – solr path, solr service name, configsets path, instance name for sitecore, SQL instance name and login credentials.

  • XP0-SingleDeveloper.ps1
  • XP0-SingleDeveloper.json
  • xconnect-solr.json
  • sitecore-solr.json

Step 4: Install prerequisites

Install-SitecoreConfiguration -Path .\Prerequisites.json

Step 5: Install Sitecore 9.1

  • Execute the script ./XP0-SingleDeveloper.ps1 (takes good amount of time to execute)
  • Fingers crossed!

Note: There is no ‘b’ admin password. You can get the password at the end of the script execution. Nice work Sitecore!

Notice that it installed the third site in IIS – Identity Server (New to 9.1)

Also noticed the http://[sitename]/sitecore/login now redictes to identiyserver in the URL.

Have fun exploring Sitecore 9.1!

Any questions, please leave a comment.

0

Sitecore 9 Forms: Redirecting to formbuilder on Submit?

Problem:

Have you submitted a form and it redirected to form builder url and displayed without styles? If so, here is the solution

Resolution:

  • Make sure to add these scripts to MVC OuterLayout.cshtml and reference it in MVCLayout.cshtml. More details, refer the documentation (Steps 3 and 4)
@using Sitecore.ExperienceForms.Mvc.Html  

@Html.RenderFormStyles()
@Html.RenderFormScripts() 

Any questions, please leave a comment. Happy sitecoring!

0

Sitecore Certification : Exam and Review

I recently took the Sitecore 9.0 Certified Platform Associate Developer exam online and passed with overall score of 88%.

Here are the steps I have taken to become certified:

Architecture: 100%
Creating and Editing Items: 100%
Development Environment: 75%
Docs and Support: 100%
Installation: 100%
Publishing: 100%
xManagement: 100%
Field Types: 83%
Media: 100%
Templates: 85%
Versioning: 100%
Presentation: 77%
API: 100%
Modules and Packages: 100%
Performance: 100%
Search: 80%

  • Once you complete you exam, you will receive an email from test center with score and certification pdf file. Good luck!

Note:

  • Sitecore Professional Developer – This examination is for Version 8.2
  • Sitecore Certified Platform Associate Developer – This is for Version 9.0

0

Tips and Tricks : GIT Cherry Pick

I came across a situation where I need to merge only couple of commits from branch(not the entire branch) and Git cherry pick does the job pretty clean. I use Git extensions IDE and context menu makes it easier.

Here are the steps:

  • Make sure you checkout the branch you want to merge the commits
  • Navigate to the commit you want to cherry pick
  • Right click and select cherry pick commit option

  • It opens a dialog with the option to choose auto commit and add commit reference. I recommend checking both of them. By default, they are not checked. Hit Cherry pick button.
  • Now the commit is auto committed and ready to be pushed into current branch.

Happy cherry picking!

0

Sitecore 9 Forms: Custom Submit Action

One of most common scenario I came across in Sitecore 9 Form is to create your custom submit action. You can achieve this in three simple steps.

Here is a video of how to create Custom Submit Action.

Step 1: Create submit action button in Sitecore

Create the custom action button under /sitecore/system/Settings/Forms/Submit Actions.

Step 2: Create code behind class

Create a class that inherits SubmitActionBase class and override the Execute method.

public class CustomSubmitAction : SubmitActionBase<string>
{
public CustomSubmitAction(ISubmitActionData submitActionData) : base(submitActionData)
{
}

public override void ExecuteAction(FormSubmitContext formSubmitContext, string parameters)
{
Assert.ArgumentNotNull((object)formSubmitContext, nameof(formSubmitContext));

if (this.TryParse(parameters, out string target))
{
try
{
if (this.Execute(target, formSubmitContext))
return;
}
catch (ArgumentNullException ex)
{
}
}
formSubmitContext.Errors.Add(new FormActionError()
{
ErrorMessage = this.SubmitActionData.ErrorMessage
});
}

protected override bool Execute(string data, FormSubmitContext formSubmitContext)
{
Assert.ArgumentNotNull(data, nameof(data));
Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

//Prepare model here
var model = new EmailModel()
{
Email = GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("EmailAddress")))
};

// Call any API service call

return true;
}

private static string GetValue(object field)
{
return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;
}

protected override bool TryParse(string value, out string target)
{
target = string.Empty;
return true;
}

Step 3: Set the custom submit action fields

Update the ModelType and Error Message on the button shown below.

Bind the custom submit action to Submit button like below.

Publish the button. The submit button on form should now trigger the custom save action! Any questions, let me know.

Happy sitecoring.

0

Sitecore 9 Forms: Success message


Sitecore 9 form feature is awesome and simple to work with. It is more like Visual Studio Toolbox and you can drag and drop the fields.

I had a requirement from Client asking for Ajax form and wanted to show Confirmation/Success message after the form is submitted. Out of the box, this is achievable with the Form.

Here is a small guide on how to create a form with confirmation message:

1. Select Forms from Dashboard.

2. Click Create button.
3. Select blank form.

4. Drag a page for main content.
5. Drag a another page for confirmation message.
6. Design the fields according to needs. Here I’m doing Email Signup form. You can add field validation and css-class as needed.

Please make sure you have these scripts in Layout.cshtml.

@Html.RenderFormStyles()
@Html.RenderFormScripts()

7. On the submit button, set the Navigation step to Next instead of submit. This does the trick to show the confirmation page.

7. Save the form.
8. Now you can see the form in Content Editor.

Don’t forget to publish the form and place it on a web page under MVC layout. Here is Sitecore documentation on Adding a form to webpage.

Happy Sitecoring.

0

Pattern Matching in C# 7.0 Switch Statements

I was trying to figure out what would be the best way to list out partial views based on Model type and found C# 7.0 new feature ‘Pattern matching in switch statements’ would be great fit for the scenario.

Before only string/integer can be compared, now you can compare on any type of object. Below is the example shows switch case based on Model Interface type.

@model Synthesis.IStandardTemplateItem

@switch (Model)
{
case INavigationColumnItem nci:
//Take any action
break;
case IColumnNavigationFolderItem ncfi:
//Take any action
break;
case IHeaderLogoItem hli:
//Take any action
break;
case IHeaderNavigationLinkItem hnli:
//Take any action
break;
case IHeaderPhoneNumberItem hpni:
//Take any action
break;
}

Checkout more cool new C# 7.0 features here. Happy coding.

0

Sitecore 9 Forms: Custom Control – Conditional Section

I came across a scenario to implement Conditional Section for Sitecore 9.0 to hide/show fields based on user input. This feature was introduced on Sitecore 9.1(Checkout my other blog here). Since the project is in Sitecore 9.0, I decided to create a custom control using speak. 

Let’s get started.

Step 1: Create form element in core DB using speak

  • Switch to Core DB
  • Go to /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings
  • Create a template based of Form Parameters. (I couldn’t find it when i tried from Insert Template, so i duplicated the existed one- MutliLine Text. If you know, how to add Form Parameters template(not using Sitecore Rocks), please leave a comment.)

 

  • Add the FormTextBox Parameters template. Since I duplicated MultiLine Text field, it came with the Details, Validation, Styling and Advanced. I feel it’s best shortcut to create quick.
  • Fill out FormLabel, IsLableOnTop and BindingConfiguration fields. 
  • Repeat the fields as many as you need. Here i added one more to compare the value.
  • NOTE: IsLabelOnTop is unchecked for additional fields

Step 2: Create form template in Master DB

  • On Master DB, create a custom template under Basic/Lists/Security/Structure folders based on Field Type template(/sitecore/templates/System/Forms/Field Type). I created under Structure Section as it’s Condition Section.
  • Fill out Property Editor field by choosing the custom control that was created in Core DB. You can see all the fields listed shown in below screen shot. 
  • Fields(View Path, Model Type)will be filled out after creating code behind and razor view files.

Step 3: Create model and view in Visual Studio

  • Create model and view in project under Helix structure
    public class ConditionalViewModel : FieldViewModel
    {
        public string TargetField { get; set; }
        public string TrueValue { get; set; }

        protected override void InitItemProperties(Item item)
        {
            base.InitItemProperties(item);

            TargetField = StringUtil.GetString(item.Fields["Target Field"]);
            TrueValue = StringUtil.GetString(item.Fields["Show Value"]);
        }

        protected override void UpdateItemFields(Item item)
        {
            base.UpdateItemFields(item);

            item.Fields["Target Field"]?.SetValue(TargetField, true);
            item.Fields["Show Value"]?.SetValue(TrueValue, true);
        }
    }
@using Sitecore.ExperienceForms.Models
@using Sitecore.ExperienceForms.Mvc.Html
@using Sitecore.Mvc
@model  Sitecore.Project.Example.Views.CustomControl.ConditionalViewModel

@{
    var viewModel = Model is IViewModel vModel ? vModel : null;
}

<div @(Sitecore.Context.Request.QueryString["sc_formmode"] != null ? "" : "hidden") class="@Model.CssClass cond-@Model.targetField-@Model.trueValue">
    @Html.RenderFields(viewModel)
</div>

@if (Sitecore.Context.Request.QueryString["sc_formmode"] == null)
    {
        <script type="text/javascript">
            const condArr = [];

            function initConditional() {
                const conditionals = document.querySelectorAll('[class*="cond-"');
                conditionals.forEach((e) => {
                    e.className.split(" ").forEach((c) => {
                        if (c.includes('cond-')) {
                            condArr.push(parseClassName(c));
                        }
                    });
                });
                condArr.forEach((cond) => {
                    const element = document.getElementsByClassName(cond.field_name)[0];
                    element.setAttribute("data-cond", cond.field_name);
                    element.onchange = () => {
                        conditionalChange(element, condArr);
                    }
                });
            }

            function conditionalChange(element, condArr) {
                condArr.forEach((cond) => {
                    if (cond.field_name === element.getAttribute("data-cond")) {
                        if (cond.value === element.value) {
                            document.getElementsByClassName(cond.class)[0].removeAttribute("hidden");
                        } else {
                            document.getElementsByClassName(cond.class)[0].setAttribute("hidden", "true");
                        }
                    }
                })
            }

            function parseClassName(class_name) {
                const arr = class_name.split("-");
                if (arr.length < 3) {
                    console.log(`Malformed className: ${class_name}`);
                } else {
                    const obj = {
                        class: class_name,
                        field_name: arr[1],
                        value: arr[2]
                    }
                    return obj;
                }
            }

            initConditional();
        </script>

Step 4: Update the template fields

Now you should see the new form control on the elements panel. Drag and Drop to any form and fill out the Target Field and True Value fields appropriately and put any element(s) inside Conditional Section to show/hide the element(s).

Don’t forget to publish all the templates and forms!

Happy Sitecoring! Leave a comment if you have any questions.

0