Monday, May 29, 2017

How to: Sitecore facet on comma separated single-line text

Intro:


How difficult is it to find a quick code example to implement facets on “Single-Line Text-field” in Sitecore using Lucene search? Well, I had to search at least 15~20 min to find the answer.
Even the one I found is not exactly what I was looking for. Again, I was looking for quick code snippet that I can insert into my code and continue on my business logic vs technically understanding how contest search Api works. So, that is the backdrop for this post.

What will you see in this post:
In this post I would like to share a quick code snippet of how exactly to use a single-line text field for faceting using Lucene.

Single-line text in Sitecore:


Singe line text field with comma separated values 


Code snippet:

using (var context = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
    results = context.GetQueryable<SearchResultItem>()
                        .Where(sri => sri.Parent == Sitecore.Data.ID.Parse(Guid.Parse("{2E8565A9-24EC-441A-8D44-EA47779D5B05}"))) //product repo parent
                        .Where(i => i.TemplateId == Sitecore.Data.ID.Parse(Guid.Parse("{535C290E-4053-4E5F-8E62-372C2304AA30}")))
                        .FacetOn(f => f["ProductCategory"]).GetResults();
                    //For every facet that you want, just continue to use the FacetOn()
}


In the above code, I was not sure on how to set the item for Search context. So, I used the ‘item.parent’ clause to restrict the items returned. Let me know in comments if there is any better method.

Unexpected issue:

After setting up the above, I was sure my code will execute. However, the demo gods were not on my side. I ran into below issue.

[NullReferenceException: Object reference not set to an instance of an object.]
   Sitecore.ExperienceExplorer.Business.Pipelines.HttpRequest.EnableExperienceModePipeline.Process(HttpRequestArgs args) +950
   (Object , Object[] ) +73
   Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +483
   Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +21
   Sitecore.Nexus.Web.HttpModule.’ (Object  , EventArgs  ) +531
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +91


Root cause for this issue is because of my overridden setting of ‘website’ site in my custom config as below
<sites>
      <site patch:instead="site[@name='website']"
            name="website"
            virtualFolder="/"
            physicalFolder="/"
            rootPath="/sitecore/content/MyRoot "
            startItem="/home"
            database="web"
            domain="elasticpath"
            allowDebug="true"
            cacheHtml="true"
            htmlCacheSize="50MB"
            registryCacheSize="0"
            viewStateCacheSize="0"
            xslCacheSize="25MB"
            filteredItemsCacheSize="10MB"
            enablePreview="true"
            enableWebEdit="true"
            enableDebugger="true"
            disableClientData="false"
            cacheRenderingParameters="true"
            renderingParametersCacheSize="10MB"/>
    </sites>
Once I removed the highlighted it started working again. Any explanations from Sitecore community?

More information on above error is available on blog below
http://codingdennis.blogspot.in/2017/02/sitecoreexperienceexplorerbusinesspipel.html

Hope this blog comes handy to someone in future


Tuesday, January 31, 2017

Sitecore MVPs for 2017 announced


Today Sitecore announced their 2017 MVPs list. I am glad an honored to receive the award for this year. Would like to congratulate other Sitecore MVP. You can access the full list of Sitecore MVPs here. 

https://www.sitecore.net/mvp

This being my first Sitecore MVP award, I am very much excited to engage even more now with Sitecore community and learn about Sitecore more closely.

Below is quick world chart of Sitecore MVP by Country

https://docs.google.com/spreadsheets/d/1unqgNibvlLdsJ_DHVhLHI820Q_1hdgs_tlLNB_Nv3yY/pubchart?oid=1249805955&format=interactive

and Award by Category type

https://docs.google.com/spreadsheets/d/1unqgNibvlLdsJ_DHVhLHI820Q_1hdgs_tlLNB_Nv3yY/pubhtml?gid=479490674&single=true

Monday, January 23, 2017

Steps to implement Coveo Exlusion Filter

Last year when we were setting up Coveo search for a site an issue was brought to attention by my colleague @MadhuAkkireddy. The 404 and error pages are being indexed and we wanted to exclude them from index.

Below is the environment information

Environment:
1. Sitecore 8.1 update 3
2. Coveo for Sitecore 7 Free version.

 We performed below steps to remove the item from index
Add an exclusion filter

Exclusion filter added to Index

 If the items to exclude can be captured through a regular expression pattern, Coveo provides a feature to configure same

Using regular expression for exclusion filters


Unfortunately this did not solve the problem. we were still seeing the errors. We cleared the cache on website. But still not the expected result. Then after sometime we started to do deduct all the factors that can lead to this situation. Out of that we captured below steps to setup exclusion filter properly.

Steps

  1. In Coveo Admin panel, under content menu, Index browser, right click the item to exclude and click "Add an Exclusion Filter"
  2. Under Index Menu, Sources and Collections, ensure that item is appearing under Filters section
  3. To exclude more than 1 item that follows a pattern, you can use regular expression filters
  4.  Perform re-build index from Sitecore control panel

The Key to our issue was that we were performing indexing on Coveo and cache clear at Sitecore Sitecore end respectively. But what we were missing is to trigger a re-build index from Sitecore control panel. Once we did it, we solved the issue and were ready to face our next challenges.

Perform Re-index on Sitecore Control Panel


The same was mentioned in Coveo site as below
"If you have previously indexed items that are now excluded with your newly created processor, those items will be deleted from the index once you re-index them. If you want to completely remove all those undesired items from your index, you will have to trigger a rebuild from the Indexing Manager (in the Sitecore Desktop, access Control Panel > Indexing > Indexing Manager)." - Coveo
The reason for this blog is, at one point we went to a stage where we wanted to write custom pipelines for exclusion filters. However, we did a deduction brainstorming to avoid customization and ended up with above notes from Coveo on their site. Though the issue is very small in terms of fixing, it is very important to have overall understanding of the product you are working on. This will avoid customizing the original product for typical requirements. Saves you time and your clients investment.

You can do further reading on how to use pipelines for creating exclude filters in Coveo by follwing below URL.

https://developers.coveo.com/display/public/SitecoreV4/Excluding+Sitecore+Items+from+Your+Index
You can share situations like above in below comments. Will be looking forward to learn more from what situations you faced during your work. And also, I suggest you join the Sitecore slack channel where we have channels with great Sitecore developers discussing each and every aspect of Sitecore.

Thursday, December 1, 2016

Solved Experience Editor JS issue with SxA Sitecore 8.2


During my preparation for Sitecore User Group meetup Hyderabad, I faced a challenge to demonstrate the SxA features. The issue was when I open up the Experience editor and switch the menu tabs nothing happens.

  1. I don't see the floating toolbox on the left that comes with SxA
  2. When I click on tabs nothing happens

Check the screenshot below

Menu click view and Experience Accelerator


Now, I wanted to solve this issue before the meetup. So, I started digging into the JS errors that appeared. Opened the F12 developer tools on Chrome and noticed the errors as shown in image below.

JS issues in Experience Editor with SXA


As you can see, there is a  Failed to load resource: /Styles/DragAndDrop/zgmover.css. I did a quick search in my Sitecore tree for the name 'zgmover' and found an item in the location "/sitecore/media library/Base Themes/Editing Theme/Styles/zgmover". So, I downloaded the file and placed it in the location "styles/DragAndDrop/" under website root folder.

This solved the resource load failed issue. But the Tab issue and floating toolbar are still not available. So, the next step is to stop bundling the JS file to locate which js-file has the issue.

So, after couple of searches in confg files, I found the below config file under App_Config/include folder
Sitecore.ExperienceEditor.config

The setting I updated the value to false is <setting name="WebEdit.EnableJSBundling" value="true" />
Once I did that, I was able to locate the issue is with "..\Website\sitecore\shell\Applications\Page Modes\LayoutDefinition.js"

After debugging the JS file, I was able to identify the issue at line number 39. The line has a for loop that iterates over the renderings of the device. And as there are no renderings it was throwing the
Uncaught TypeError: Cannot read property 'length' of error

I have updated the code @line 39 as below and soon the issue is resolved. When I asked about this issue in Sitecore slack chat I got a response that Sitecore ticket is already created for this. However, I don't have the details. Once I get those I can update here in the blog.

if(device.r !== undefined)
{
 for (var n = 0; n < device.r.length; n++) 
 {
   device.r[n]["controlId"] = "r_" + this.getShortID(device.r[n]["@uid"]);
   renderings.push(device.r[n]);
 }
}

Here is the screen with floating toolbar. Day saved :)
Floating Toolbar of SxA

Wednesday, November 30, 2016

A pipeline dive into Sitecore Personalization using Conditional Renderings


“I have no special talents. I am only passionately curious.” -Albert einstein

I recently encountered a question in Sitecore.stackexchange.com. Question is about how to retrieve the Default Datasource and personalized datasource for a rendering component that has Conditional Rendering personalization rule. Link to Question is below


As the quote above says, I got passionately curious to understand How Sitecore Stuff works behind the scenes for personalization by Conditional Renderings. So, I started digging and opened my favorite .NET Tool dotPeek

So, here is the magic(read pipelines and processors) behind Conditional Renderings.


For those who are not aware,

Any renderings we add onto page resides in PlaceHolder. So, we will start looking from rendering them and go deeper. Though there is lot more that will happen ahead of placeholder rendering, we will omit it for keeping this post simple. Inside the <mvc.renderPlaceholder> pipeline there is a processor called "PerformRendering".

PerformRendering processor calls the pipeline <mvc.renderRendering> pipeline. This pipeline will call the corresponding render for rendering the content. And this is the point of discussion for this blog post.

In order to identify the Renderer Sitecore calls the <mvc.getRenderer> pipeline. There is a processor inside this pipeline called "Sitecore.Mvc.Analytics.Pipelines.Response.GetRenderer.CustomizeRendering".

This pipeline internally calls another pipeline <mvc.customizeRendering>. Inside this pipeline we have a processor called "Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering.Personalize". This is the processor checks if the Tracker is Active to run the pipeline and is responsible for running the rules and applying the actions.

This processor calls the <getRenderingRules> pipeline to get the rules from the underlying rendering. Here it looks in the rendering.Properties["RenderingXml"] for retrieving the personalization rules associated with in the rendering.

Perosonalization Rules from Rendering
 
 
There are 3 events  namely Evaluating, Evaluated and Applied. One can hook to these events and drive any custom tasks to perform. Out-of-Box Sitecore uses the Evaluated event and runs the <renderingRuleEvaluated> pipeline.

Because by the time the controller receives the Rendering details all the personalization rules are applied there is a pecking order for the Rendering DataSource and below is how it picks

  1. DataSource selected in the Action section of Rule that is applied
  2. The order of Default DataSource will be
    1. DS selected in the Action section
    2. If Action Section is empty, then DS selected from Rendering Parameters
    3. If none of them are set then RenderingReference.Settings.DataSource is empty. But the actual Rendering DataSource set to PageItem


Now that we know the pipelines and their relation it can be used to introduce custom rule evaluating or rule applied pipelines for further customization. 

Please share your thoughts on what you think about the blog.

Friday, November 18, 2016

26 Accepted questions on Coveo for Sitecore

Knowledge is wealth. And creating that wealth of knowledge and maintaining it is not an east feat.

Everyday there are so many questions asked, reviewed, suggested and answered in sitecore.stackexchange.com. So, I wanted to tap into this knowledge to put it to good use. While SSE gives us an option to see the unanswered questions, I feel there should be a option to see the accepted questions. Or have an option to search only in answered questions. This can sometimes help reduce the noise and see if a question is answered and accepted.

While writing this blog, I asked the same question in sitecorechat.slack.com under #stackexchange channel. And what do you expect? It was answered in few seconds. Shows how useful slack is sometimes right?

Not just answering the question dmytro also showed the path for creating queries in stackexchange
Here is simple query which pulls all the accepted answers under Sitecore site.

http://data.stackexchange.com/sitecore/query/580262/accepted-questions

Query for the above goes like this
SELECT
  Posts.Id AS [Post Link]
FROM
  Posts
WHERE
  PostTypeId = 1
  AND AcceptedAnswerId > 0
ORDER BY
  Id DESC
Results can be downloaded in .csv file format. This can be extremely helpful in maintaining the knowledge base and utilizing same in training.

If you want to play around then you can create new queries using the link below
http://data.stackexchange.com/sitecore/query/new

Well back to my post after a useful deviation, here are the google slides that I created from sitecore.stackexchange.com for accepted questions with Coveo tag. Though we can run our own queries as suggested above it always feels good if the content is curated and made available for easy consumption. And one such effort I tried below.

If you wish to look at the original conversation,  you click on the question and it will link you back to stack exchange site for details.


Tuesday, November 8, 2016

A primer on Sitecore Data Exchange Framework

On Nov 8, 2016 there was a live session on Sitecore Data Exchange Framework with Nate Barad (Senior Director of Product Marketing) and Adam Conn (Director of Technical Product Management) on Sitecore YouTube channel. It was a great session demonstrating the flexibility of Sitecore supporting complex applications. In this case it no less than developing an ETL on Sitecore.

Here is the link to YouTube Video

What is Sitecore Data Exchange Framework (DEF)


Data Exchange Framework: 

"At the highest level DEF is a Product that aims to make it as easy as possible for the people to be able to connect different systems for the purpose of sharing data." - Adam Conn, Director of Technical Product Management Sitecore.

Sitecore can take the role of both Source and Destination as per the need.

Need for DEF


partners and clients are developing integration solutions and multiple ways. This leads to inconsistencies and one-time solutions. So, DEF was created to give a consistent approach for 
  • Reading, Writing, mapping data (ETL)
  • Maintain flexibility of current approaches
  • Minimal dependency on Sitecore at runtime
  • Minimal Sitecore expertise needed to develop provider

Difference between DataProvider, DEF  and xConnect


DataProvider: Was available in older versions of Sitecore. Helps create or display external data in Sitecore as Items. Lot of plumbing code to be developed for implementing each DataProvider. Mapping, reading and writing logic all handled by same component.

DEF: Dependent on DataProvider logic for retrieving the data. Has Sitecore Item based configuration model for performing the mapping logic and execution of data exchange process. Compatible with Sitecore 8.1 and above only.

xConnect: An abstraction layer for interacting with Sitecore Items. Using xConnect, developers need to know only about the external system and its schema. DEF can relay the data to xConnect to handle the creation, edit and delete actions. Not yet available from Sitecore. May release with Sitecore 8.3.


Installation steps


Download the below files and install in same order from dev.sitecore.net
  1. Data Exchange Framework 1.1
  2. Sitecore Provider for Data Exchange Framework 1.1
  3. Sitecore Provider for Data Exchange Framework 1.1 Hotfix 128342


Installed Items


Under System a new  Data Exchange is created which has insert options to create a new Data Exchange Tenant. All the action happens under Tenants. Once a new tenant is created below items are automatically created.
  • Endpoints: For defining the source and destination providers
  • Data Access: For defining the value accessor sets
  • Value Mapping Sets: For defining the mapping between the source and destination value accessor sets
  • Pipelines: For configuring the flow of logic. 
  • Pipeline Batches: Object to run the synchronization
  • Queues
  • Tenant Settings

Items created for Data Exchange Framework

Things to remember with DEF

By default the pipelines batches are not enabled. This helps prevent accidentally running the batch in design stage. Verify the below before running the pipeline batch for success
  1. Tenant is enabled
  2. Pipeline batch is enabled - Will be eligible for enable only if the Tenant is enabled
  3. Pipeline should be enabled
  4. Ensure the sort order of the pipeline processors


Advantages


  • Promotes a component design
  • Reuse of pipelines, endpoints, value accessor and mapping sets
  • Easy to accomdate any changes in Source and Destination schema changes
  • User interface validation for datatypes and fields


Cons

  • Not an intuitive process. So, need developers for defining process, mapping and value sets
  • No drag-and-drop UI for creating source and destination mappings
  • Need to know the source and destination schema first
  • Lot of manual item creation for simple process also

In conclusion, DEF is a powerful tool which give the development team the ability to perform ETL activities without much coding. Tool being in it's early stages and no UI similar to other BI/ETL tools may have less adoption. For projects with requirements to connect to only single system for data exchange this can become a handy tool but enterprise projects that have multiple integrations will incline towards a commercial ETL tool like Informatica, Scribe and similar.