output
stringlengths 34
25.7k
| instruction
stringlengths 81
31k
| input
stringclasses 1
value |
---|---|---|
The following PowerShell script can be made available as a Web API endpoint within Sitecore. Instructions on how to do this are documented in the script:
# Reconnect Sitecore Commerce catalog
# https://www.sergevandenoever.nl, https://www.linkedin.com/in/sergevandenoever/
#
# Execute the manual steps to correctly reconnect a catelog when a Sitecore XC Initialize is executed
# These steps are:
# - Unselect Catalog
# - Select Catalog
# - Set Catalog Templates
# - Delete Data Templates
# - Update Data Templates
# - Rebuild Search Index
#
# Deployment of script as Web API endpoint:
# In Content Editor, navigate to /sitecore/system/Modules/PowerShell/Script Library
# Right-click on "Script Library" and select: Insert > Module Wizard
# - Name the module (e.g. name of customer - for example customer)
# - For integration points to create select "Web API"
# Right-click on the folder /sitecore/system/Modules/PowerShell/Script Library/<customer name>/Web API
# and select: Insert > PowerShell Script and name the script customer_ReconnectCatalog.ps1
#
# This will result in a Web API end-point on the Content Management server.
#
# Usage:
# https://customer_cm.com/-/script/v2/master/customer_ReconnectCatalog
#
# Querystring parameters:
# - sitepath: Sitecore path to site where to reconnect catalog
# - catalogname: Name of the catalog to reconnect
# - wait: 0,false,1,true - if 1 or true, wait for the index job to finish
#
# Example:
# https://customer_cm.com/-/script/v2/master/customerc_ReconnectCatalog?sitepath=/sitecore/content/MyTenant/MySite&catalogname=MyCatalog&wait=1
#
$global:debug = $false
$global:log = @()
$global:stopwatch = [system.diagnostics.stopwatch]::startNew()
function Log {
param (
[string]$message
)
if ($debug) {
Write-Output $message
}
$global:log += $message
}
function SelectCatalog {
param (
[string]$SitePath,
[string]$CatalogName
)
$catalogsItemPath = "$SitePath/Home/Catalogs"
Log "Select catalog $CatalogName"
$catalogsItem = Get-Item -Path $catalogsItemPath
$catalogsItem.Editing.BeginEdit() | Out-Null
$catalogsItem['Selected Catalogs'] = $CatalogName
$catalogsItem.Editing.EndEdit() | Out-Null
}
function UnselectCatalog {
param (
[string]$SitePath,
[string]$CatalogName
)
$catalogsItemPath = "$SitePath/Home/Catalogs"
Log "Unselect catalog $CatalogName"
$catalogsItem = Get-Item -Path $catalogsItemPath
$catalogsItem.Editing.BeginEdit() | Out-Null
$catalogsItem['Selected Catalogs'] = ''
$catalogsItem.Editing.EndEdit() | Out-Null
}
function SetCatalogTemplates {
param (
[string]$SitePath,
[string]$CatalogName
)
Log "Set catalog templates for catalog $CatalogName"
Import-Function Get-TenantItem
Import-Function Get-TenantTemplate
$Site = Get-Item -Path $SitePath
$CommerceBundleTemplateName = "Commerce Bundle"
$CommerceCategoryTemplateName = "Commerce Category"
$CommerceProductTemplateName = "Commerce Product"
$CommerceProductVariantTemplateName = "Commerce Product Variant"
$CommerceDynamicBundleTemplateName = "Commerce Dynamic Bundle"
$SiteCatalogRelativePath = "/Home/Catalogs/$CatalogName"
$Tenant = Get-TenantItem $Site
$TenantTemplatesRootID = $Tenant['Templates']
$TenantTemplatesRoot = Get-Item -Path master: -ID $TenantTemplatesRootID
$TenantTemplates = Get-TenantTemplate $TenantTemplatesRoot
$CommerceBundleTemplate = $TenantTemplates | Where-Object {$_.Name -eq $CommerceBundleTemplateName} | Select-Object -First 1
$CommerceCategoryTemplate = $TenantTemplates | Where-Object {$_.Name -eq $CommerceCategoryTemplateName} | Select-Object -First 1
$CommerceProductTemplate = $TenantTemplates | Where-Object {$_.Name -eq $CommerceProductTemplateName} | Select-Object -First 1
$CommerceProductVariantTemplate = $TenantTemplates | Where-Object {$_.Name -eq $CommerceProductVariantTemplateName} | Select-Object -First 1
$CommerceDynamicBundleTemplate = $TenantTemplates | Where-Object {$_.Name -eq $CommerceDynamicBundleTemplateName} | Select-Object -First 1
$CatalogItemPath = $Site.Paths.Path + $SiteCatalogRelativePath
$CatalogItem = Get-Item -Path $CatalogItemPath
if ($CatalogItem) {
$CatalogItem.Editing.BeginEdit() | Out-Null
$CatalogItem["CategoryTemplate"] = $CommerceCategoryTemplate.ID
$CatalogItem["ProductTemplate"] = $CommerceProductTemplate.ID
$CatalogItem["ProductVariantTemplate"] = $CommerceProductVariantTemplate.ID
$CatalogItem["StaticBundleTemplate"] = $CommerceBundleTemplate.ID
$CatalogItem["DynamicBundleTemplate"] = $CommerceDynamicBundleTemplate.ID
$CatalogItem.Editing.EndEdit() | Out-Null
}
else {
Throw "SetCatalogTemplates: Catalog '$CatalogName' not found"
}
$serviceLocatorInstance = [Sitecore.DependencyInjection.ServiceLocator]::ServiceProvider
$dataProviderService = $serviceLocatorInstance.GetType().GetMethod('GetService').Invoke($serviceLocatorInstance, [Sitecore.Commerce.XA.Foundation.Common.Services.CEConnect.IDataProviderService])
$dataProviderService.ClearCommerceCache() | Out-Null
}
# This function sometimes fails on first call, so using retry
function DeleteDataTemplates {
$maxRetryCount = 5
$retryCount = 0
$done = $false
Log "Delete Data Templates - Begin"
Do {
try {
$masterDatabase = Get-Database -Name "master"
[System.Reflection.Assembly]::LoadWithPartialName("Sitecore.Commerce.Engine.Connect") | Out-Null
$catalogTemplateGenerator = New-Object -TypeName Sitecore.Commerce.Engine.Connect.DataProvider.Templates.CatalogTemplateGenerator
$catalogTemplateGenerator.DeleteAllGeneratedTemplates($masterDatabase)
$done = $true
} catch {
Log "Exception: $_"
$retryCount++
Log "Retry $retryCount of $maxRetryCount"
}
} While ((-not $done) -and $retryCount -lt $maxRetryCount)
if (-not $done) {
Log "===== FAILED ====="
} else {
Log "===== SUCCESS ====="
}
Log "Delete Data Templates - End"
}
function UpdateDataTemplates {
Log "Update Data Templates - Begin"
$masterDatabase = Get-Database -Name "master"
[System.Reflection.Assembly]::LoadWithPartialName("Sitecore.Commerce.Engine.Connect") | Out-Null
$catalogTemplateGenerator = New-Object -TypeName Sitecore.Commerce.Engine.Connect.DataProvider.Templates.CatalogTemplateGenerator
$catalogTemplateGenerator.BuildCatalogTemplates($masterDatabase) | Out-Null
Log "Update Data Templates - End"
}
function IndexCatalog {
param (
[string]$IndexName = 'sitecore_master_index'
)
Log "Rebuild search index $IndexName"
$jobId = Rebuild-SearchIndex -Name sitecore_master_index -AsJob |
ForEach-Object { $_.Handle.ToString() }
$jobId
}
function GetSitecoreJobStatus {
param (
[string]$JobId
)
$job = [Sitecore.Jobs.JobManager]::GetJob([Sitecore.Handle]::Parse($JobId))
$isDone = $job -eq $null -or $job.IsDone -or $job.Status.Failed
$status = "No longer exists"
$jobName = $JobId
if($job) {
$jobName = $job.Name.Replace("Index_Update_IndexName=", "")
$state = $job.Status.State
$processed = $job.Status.Processed
if($job.Options -and $job.Options.CustomData -is [Sitecore.Publishing.PublishStatus]) {
$publishStatus = $job.Options.CustomData -as [Sitecore.Publishing.PublishStatus]
if($publishStatus.Processed -gt 0) {
$state = $publishStatus.State
$processed = $publishStatus.Processed
}
}
$status = "$($state) and processed $($processed)"
}
[PSCustomObject]@{
"Name" = $jobName
"IsDone" = $isDone
"Status" = $status
}
}
function WaitForSitecoreJob {
<#
.SYNOPSIS
Polls for the specified job until it has completed.
.DESCRIPTON
The WaitForSitecoreJob command waits for a Sitecore.Jobs.Job to complete processing.
.PARAMETER JobId
The Sitecore JobId to poll.
.PARAMETER Delay
The polling interval in seconds.
#>
[CmdletBinding()]
param(
[ValidateNotNull()]
[string]$JobId,
[int]$Delay = 1
)
$keepRunning = $true
while($keepRunning) {
$response = GetSitecoreJobStatus -JobId $JobId
if($response -and $response.IsDone) {
$keepRunning = $false
Log "Polling job $($response.Name). Status : $($response.Status)."
Log "Finished polling job $($id)."
} else {
Log "Polling job $($response.Name). Status : $($response.Status)."
Start-Sleep -Seconds $Delay
}
}
}
# $VerbosePreference = "Continue"
[System.Web.HttpContext]::Current.Response.ContentType = "application/json"
try {
if ($debug) {
[string]$SitePath = "/sitecore/content/MyTenant/MySite"
[string]$CatalogName = "MyCatalog"
[boolean]$WaitForJob = $true
} else { # use query string parameters
[string]$SitePath = [System.Web.HttpContext]::Current.Request.QueryString['sitepath']
[string]$CatalogName = [System.Web.HttpContext]::Current.Request.QueryString['catalogname']
[string]$wait = [System.Web.HttpContext]::Current.Request.QueryString['wait']
if ([String]::IsNullOrWhiteSpace($SitePath)) {
Throw "Url parameter sitepath is missing"
}
if ([String]::IsNullOrWhiteSpace($CatalogName)) {
Throw "Url parameter catalogname is missing"
}
[boolean]$WaitForJob = $false
if (![String]::IsNullOrWhiteSpace($wait) -and ($wait.ToLower() -eq 'true') -or ($wait -eq '1')) {
$WaitForJob = $true
}
}
Log "========= BEGIN RECONNECTING CATALOG $CatalogName ========="
UnselectCatalog -SitePath $SitePath -CatalogName $CatalogName
SelectCatalog -SitePath $SitePath -CatalogName $CatalogName
SetCatalogTemplates -SitePath $SitePath -CatalogName $CatalogName
DeleteDataTemplates
UpdateDataTemplates
$jobId = IndexCatalog -IndexName 'sitecore_master_index'
if ($WaitForJob) {
WaitForSitecoreJob -JobId $jobId -Delay 10
$jobId = ''
}
Log "========= END RECONNECTING CATALOG $CatalogName ========="
$global:stopwatch.Stop()
@{
process = "ReconnectingCatalog"
sitepath = $SitePath
catalogname = $CatalogName
success = $true
jobId = $jobId
log = $log
duration = $global:stopwatch.Elapsed.ToString()
} | ConvertTo-Json
} catch {
Log "Exception: $_"
$global:stopwatch.Stop()
@{
process = "ReconnectingCatalog"
sitepath = $SitePath
catalogname = $CatalogName
success = $false
exception = $_.ToString()
log = $log
duration = $global:stopwatch.Elapsed.ToString()
} | ConvertTo-Json
[System.Web.HttpContext]::Current.Response.StatusCode = 500
[System.Web.HttpContext]::Current.Response.TrySkipIisCustomErrors = $true
}
The Web API call returns a JSON object with status and log information. In case of success the HTTP status code is 200, in case of error the HTTP status code is 500.
Example of the JSON result:
{
"success": true,
"jobId": "",
"sitepath": "/sitecore/content/MyTenant/MySite",
"log": [
"========= BEGIN RECONNECTING CATALOG MyCatalog =========",
"Unselect catalog MyCatalog",
"Select catalog MyCatalog",
"Set catalog templates for catalog MyCatalog",
"Delete Data Templates - Begin",
"===== SUCCESS =====",
"Delete Data Templates - End",
"Update Data Templates - Begin",
"Update Data Templates - End",
"Rebuild search index sitecore_master_index",
"Polling job sitecore_master_index. Status : Running and processed 0.",
"Polling job sitecore_master_index. Status : Running and processed 2105.",
"Polling job sitecore_master_index. Status : Running and processed 6191.",
"Polling job sitecore_master_index. Status : Running and processed 10345.",
"Polling job sitecore_master_index. Status : Running and processed 13075.",
"Polling job sitecore_master_index. Status : Running and processed 18163.",
"Polling job sitecore_master_index. Status : Finished and processed 20593.",
"Finished polling job .",
"========= END RECONNECTING CATALOG MyCatalog ========="
],
"duration": "00:01:26.8856534",
"catalogname": "MyCatalog",
"process": "ReconnectingCatalog"
}
To call this in your DevOps release pipeline, you can create a step in your task group of type Azure PowerShell with an inline script like below:
# Only need to reconnect catalog if the Sitecore XC system has got a bootstrap, initialize, clean
if ($(xc-initialClean)) {
$result = Invoke-WebRequest -Uri "https://customer_cm.azurewebsites.net/-/script/v2/master/customer_ReconnectCatalog?sitepath=/sitecore/content/MyTenant/MySite&catalogname=MyCatalog&wait=1&user=admin&password=$(sitecoreAdminPassword)"
if ($result.StatusCode -ne 200) {
Throw "Request to url '$Url' failed with status code $($result.StatusCode)"
[Environment]::Exit(1)
}
}
Note the $(sitecoreAdminPassword) variable used in the Url.
|
How can I automate the reconnect of a Sitecore XC catalog after initialize of Commerce Engine?
Working with Sitecore XC, we need to reconnect the commerce catalog every time we do an initialize of the Commerce Engine. We can do this initialize optionally during development. We need to execute the following steps in the Sitecore XP UI:
Unselect Catalog
Select Catalog
Set Catalog Templates
Delete Data Templates
Update Data Templates
Rebuild Search Index
How can these steps be automated in a way that can be used on the local development machine, but also in a DevOps release pipeline?
| |
As per the documentation that you can find here:
The Sitecore IP Geolocation service is free of charge and with
unlimited lookups per month.
edit
Just to clarify there is no timelimit to this, so this is not a trial period where you have to pay after a certain amount of time.
|
What is a cost for Sitecore IPGeolocation Service?
We would like to enable the geolocation service for our license. While on checking with the official documentation it looks like it is free of cost. But will it cost for using the service after some time period? Want to confirm the information regarding of the cost of service.
Thanks in advance
| |
Let me share my thoughts about your question.
I think if you need to duplicate something - stop and think about what you did wrong :)
Move functionality into Foundation Layer - is a better idea for this if you cannot re-architecture your approach or feature.
Probably, you can make an abstraction that doesn't depend on a feature and move it to the Foundation level. This also allows you to reuse this functionality in every feature.
Thanks for a good question that requires to think :)
|
Helix principles when using different page templates
While working on various Helix project implementations, I heard different opinions on how to deal with different page types in a Feature. I have these two examples:
Let's say that we have the Metadata feature which displays the meta title for all pages. What would be the approach if for example the meta title needs to be dynamically changed for the News items in the News feature project (these don't have a meta tile field and needs to be calculated)?
If in the News feature project there is a need to read only some fields from the ancestors (which will be used in the html), those Templates/Field being part of a different Feature, for example Themes.
What is the recommended practice in these situations? Are there any cases where a method would be duplicated in two features (like in the 2nd example) or should this always be moved to the Foundation layer?
Thanks for the help and sorry if the question is opinion based only.
| |
The installation guide for Sitecore XP 9.3.0 describes how to configure the MongoDB provider for xConnect.
To continue using the MongoDB xDB Collection database provider with Sitecore XP 9.3.0, you
must upgrade your existing MongoDB instance to version 4.0.5 – 4.0.10.
To upgrade the xDB Collection database there are some scripts that you need to run. These scripts are mentioned in the upgrade Sitecore manuals.
If you want to migrate the Analytics data from Sitecore 8.2 to Sitecore 9.3 you need to use xDB Data Migration Tool
So, as a conclusion, the old schema and data cannot be re-used in Sitecore 9.3 you need to migrate it.
|
Sitecore 8.2 Mongo Connectionstrings VS Sitecore 9.3 xConnect Connectionstrings
Sitecore XP version 8.2 comes with following MongoDB databases with connection string:
analytics
tracking.live
tracking.history
tracking.contact
We are planning to upgrade Sitecore 8.2 mongo to Sitecore 9.3 mongo.
Couple of questions came to my mind
How to use the above mongo databases in Sitecore 9.3 Xconnect.
Does mongo db schema will be differ in sitecore 8.2 mongo and sitecore 9.3 mongo?
any help or suggestion would be greatly helpful. Thanks in advance
| |
Checking the official Sitecore images tags list, it seems that the sitecore-xc0-solr-init image is missing. You should open a ticket with Sitecore Support to let them know that it is missing.
In the meantime, you can update the image name of the solr-init service in your docker-compose.yml file to use the existing sitecore-xc1-solr-init image instead (xc1 instead of xc0) or use the container deployment specs for XC1. The scaling of the XC topology should not have any impact on the Solr initialization job.
|
Sitecore Commerce installation fails in Docker
Using - Sitecore.Commerce.Container.SDK.2.0.159
We were able to successfully install Sitecore XP 10.1 in docker on our local machine running on Windows 10 64-bit.
However, when we tried to install Sitecore Commerce 10.1 in the docker, the installation fails.
There is a "solr-init" error in the process.
ERROR: for solr-init manifest for scr.sitecore.com/sxc/sitecore-xc0-solr-init:10.1-ltsc2019 not found: manifest unknown: manifest tagged by "10.1-ltsc2019" is not found
ERROR: manifest for scr.sitecore.com/sxc/sitecore-xc0-solr-init:10.1-ltsc2019 not found: manifest unknown: manifest tagged by "10.1-ltsc2019" is not found
| |
Depending on the approach this would require some custom development as ootb it is not possible. Since the pdfs links are shown in your pages, one solution would be to track the click event on them.
You could handle this from javascript and then do an ajax call to register the page event on the sitecore side, you can take a look at a step by step approach described on https://sitecorescientist.com/2019/03/26/click-tracking-with-goals-and-page-events-using-sitecore-analytics/. If you don't want to use a handler to register the event, instead build a simple api which will handle this. See the sitecore documentation on registering events https://doc.sitecore.com/developers/91/sitecore-experience-platform/en/page-events.html
Another option would be to enable FXM for your website and use the API to track the click event.
SCBeacon.trackEvent(“Page visited”)
SCBeacon.trackEvent(“Page visited”, { data: “custom data”, dataKey: “custom data key” })
You can take a look at the sitecore documentation on how to activate FXM and use the API https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/fxm-javascript-api.html
|
Tracking external downloads with Sitecore analytics
I am using Sitecore 9.1.1 with SXA 1.8.1. I have a set of pdfs stored externally but I would like to use Sitecore Analytics to register download page events when someone is downloading the documents.
What would be the easiest way to do that? It is quite straightforward to track documents that are stored inside the Media Library but are there any OOTB solution to track external links or it requires custom development?
The links to the documents are rendered on the sitecore pages either in Rich text or General link fields but the documents they are pointing to are stored on external hosting which I do not own/have control over.
| |
I would do some code changes, starting with your public Item GetItem(string dataSourceId) method. You can easily replace this without using the GetItem(dataSourceId):
public Item GetDataSourceItem()
{
return RenderingContext.CurrentOrNull.Rendering.Item;
}
To write a unittest for the datasourceItem you could have something like this:
private readonly Db _db;
private readonly NavigationRepository _navigationRepository;
public NavigationRepositoryTests()
{
_db = new Db();
_navigationRepository = new NavigationRepository();
}
[Fact]
public void GetDataSourceItem_ReturnsItem()
{
// Create test items
var dbDataSourceItem = new DbItem("Home Item", ID.NewID);
_db.Add(dbDataSourceItem);
var dataSourceItem = _db.GetItem(dbDataSourceItem.ID);
var siteContext = GetSiteContext();
using (new SiteContextSwitcher(siteContext))
{
// Inject expected item in Context
using (RenderingContext.EnterContext(new Rendering() {Item = dataSourceItem, DataSource = dataSourceItem.ID.ToString() }))
{
// Act
var result = _navigationRepository.GetRenderingDataSourceItem();
Assert.Equal(dbDataSourceItem.ID, result.ID);
}
}
}
The site context would be something like this:
private static FakeSiteContext GetSiteContext()
{
// Arrange
return new FakeSiteContext(new StringDictionary()
{
["database"] = "master",
["name"] = "YourWebsiteName",
["rootPath"] = "/sitecore/content/YourWebsite",
["startItem"] = "/Home"
});
}
You can apply something similar to your unit tests. Note that this is just an example of an approach to writing unittests that also uses SiteContext, you might not need this for your tests. Try to rewrite your unittest by having the object built with FakeDb and see if it works.
Please take a look also at How to get started with Sitecore Unit Testing with SitecoreFakeDb, https://www.mydatahack.com/creating-dbitem-with-item-id-sitecore-fakedb/ and the FakeDb documentation https://github.com/sshushliapin/Sitecore.FakeDb
|
Create Unit Tests for Testing a Component in Sitecore 10
I'm completely new in Unit testing, trying to implement Unit testing for a navigation header component using xUnit, Moq and FluentAssertions library.
Below are my code for Navigation Header implementation:
INavigationRepository
public interface INavigationRepository
{
Item GetItem(string dataSourceId);
Header GetHeader(Item item);
Footer GetFooter(Item item);
}
NavigationRepository
[Service(typeof(INavigationRepository))]
public class NavigationRepository : INavigationRepository
{
private readonly INavigationRepository m_navigationRepository;
public NavigationRepository(INavigationRepository navigationRepository)
{
m_navigationRepository = navigationRepository;
}
public Item GetItem(string dataSourceId)
{
var item = Sitecore.Context.Database.GetItem(dataSourceId);
if (item == null)
{
return null;
}
return item;
}
public Header GetHeader(Item item)
{
return CreateHeaderItem(item);
}
private List<NavigationItem> GetEvents(ReferenceField eventsRoot)
{
var Events = new List<NavigationItem>();
foreach (Item i in eventsRoot.TargetItem.Children)
{
Events.Add(GetNavigationItem(i, ItemExtensions.GetItemUrl(i)));
}
return Events;
}
private NavigationItem GetNavigationItem(Item item, string itemUrl)
{
return new NavigationItem { Item = item, ItemUrl = itemUrl };
}
private Header CreateHeaderItem(Item item)
{
ImageField logo = item.Fields[Templates.Header.Fields.Logo];
ReferenceField homelink = item.Fields[Templates.Header.Fields.HomeLink];
ReferenceField eventsRoot = item.Fields[Templates.Header.Fields.EventsRoot];
LinkField scheduleLink = item.Fields[Templates.Header.Fields.ScheduleLink];
LinkField newsLink = item.Fields[Templates.Header.Fields.NewsLink];
return new Header
{
HomelinkUrl = FieldExtensions.GetUrl(homelink),
Events = GetEvents(eventsRoot),
LogoUrl = FieldExtensions.ImageUrl(logo),
LogoAlt = FieldExtensions.ImageAlt(logo),
ScheduleLinkUrl = FieldExtensions.LinkFieldUrl(scheduleLink),
NewsLinkUrl = FieldExtensions.LinkFieldUrl(newsLink)
};
}
}
Header.cs
public class Header
{
public string LogoUrl { get; set; }
public string LogoAlt { get; set; }
public string HomelinkUrl { get; set; }
public List<NavigationItem> Events { get; set; }
public string ScheduleLinkUrl { get; set; }
public string NewsLinkUrl { get; set; }
}
NavigationItem.cs
public class NavigationItem
{
public Item Item { get; set; }
public string ItemUrl { get; set; }
}
NavigationController
public class NavigationController : Controller
{
private readonly INavigationRepository m_navigationRepository;
public NavigationController(INavigationRepository navigationRepository)
{
m_navigationRepository = navigationRepository;
}
// GET: Default
public ActionResult GetHeader()
{
Item contextItem = m_navigationRepository.GetItem(RenderingContext.CurrentOrNull.Rendering.DataSource);
var model = this.m_navigationRepository.GetHeader(contextItem);
return View(model);
}
}
Unit Test , currently I'm only testing for null item
[Fact]
public void GetHeader_ItemIsNull_ReturnsEmpty()
{
// arrange
var businessLogicFake = Substitute.For<INavigationRepository>();
var sut = new NavigationRepository(businessLogicFake);
var db = Substitute.For<Database>();
var item = CreateItem(db);
//act
var result = sut.GetHeader(item);
//assert
result.Should().BeNull();
}
private Item CreateItem(Database database)
{
var item = Substitute.For<Item>(ID.NewID, ItemData.Empty, database);
var fields = Substitute.For<FieldCollection>(item);
item.Fields.Returns(fields);
return item;
}
Test Results:
The tests are getting failed, what else do I need to include? Or am I implementing it in a wrong way?
Please guide me with the implementation and also the best practices.
Thanks a lot for the help.
| |
Yes, according to Sitecore documentation, Sitecore 9.0.1 is compatible with Solr 6.6.3:
More information can be found here:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0227897
|
Solr version compatibility with Sitecore 9.0.1
My team is planning to install Sitecore 9.0.1. We are using Solr 6.6.2 version at the moment. Due to some solr search issues we are planning to use solr 6.6.3.
Is this Solr version compatible with sitecore 9.0.1 and if we can work with this?
Thanks
| |
The problem indicates that you'r Solr is indexing letters in this case differently. You need to setup new custom field on Solr schema and define what tokenizer to use. Tokenizer logic is responsible how to index words. For example in Finnish language "e-lasku" is one word but it was indexed as "e" and "lasku". I had to create custom field with different tokenizer. If you look at the schema.xml file in Solr Core you can find "text_general" field is defined as like this:
<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
<analyzer type="index">
<tokenizer class="solr.StandardTokenizerFactory" />
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<!-- in this example, we will only use synonyms at query time
<filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
-->
<filter class="solr.LowerCaseFilterFactory" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.StandardTokenizerFactory" />
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true" />
<filter class="solr.LowerCaseFilterFactory" />
</analyzer>
</fieldType>
On the third row is tokenizer defined as StandardTokenizerFactory. That split words when "-" is on the word. This is most likely the reason also why Chinese letters are split.
You need to create your own Solr Core field and use different tokenizer. Or you can remove this tokenizer on "text_general_zh" and replace it with this:
<tokenizer class="solr.WhitespaceTokenizerFactory" />
If you want to define new field you can do it like this. Add new fieldType:
<fieldType name="text_general_zh_custom" class="solr.TextField" positionIncrementGap="100" multiValued="false">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory" />
<filter class="solr.LowerCaseFilterFactory" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory" />
<filter class="solr.LowerCaseFilterFactory" />
</analyzer>
</fieldType>
And also add this line in the same file where rest of these are:
<field name="content_custom" type="text_general_custom" indexed="true" stored="true"/>
Lastly add a custom solr index on Sitecore and make code use that field.
Hopefully this resolves your problem.
|
Solr Search Issue for Chinese Language in Sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7 and Solr version 6.6.2. we have a requirement to search the chineses content so i have created some chinese content and in the page i have added the components
Added a SXA Search box component and Search Result component on the
page.
2.Specified the Scope query to search on to.
But when i search for chinese word it is not giving the results for it but i add space between the letters it is giving the results for it.
Without Space result:
With Space between the letters:
In Solr schema i have added the below set of codes:
1.
<dynamicField name="*_txm_zh" type="text_general_zh" multiValued="true" indexed="true" stored="true"/>
In Solr config i have added the below line of code:
<lib dir="${solr.install.dir:../../../..}/contrib/analysis-extras/lucene-libs" regex=".*\.jar" />
Indexed data in solr :
Can anyone please suggest what i have to do in order to search without space and get the results.
Thanks
| |
You should change your configuration as:
<field fieldName="colortext" type="Sitecore.XA.Foundation.Search.ComputedFields.ResolvedLinks, Sitecore.XA.Foundation.Search" referenceField="color" contentField="Color"/>
After doing so, don't forget to rebuild the SXA indexes and verify that you now have a field "colortext" which has the values of the colors (not the guids).
Then you change the fieldname in the facet to be "colortext". I've had situations where I had to use the exact index name including the suffix (so like colortext_sm), so if it doesn't work try that...
But step 1 is to make sure you have the values in the index.
|
How to show the filter values in Chinese in Sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7 .we have a requirement that the filter values should get displayed in chinese language.
I have created a template with field color and data type multiroot tree list
I have changed the display names of the color items to chinese and selected those items in my data folder.
but in the frontend dropdown i am able to see the Item Id's which is splitted into multiple parts
Workaround on Gatogordo's suggestion:
I added the below code in Sitecore.XA.Foundation.Search.Solr.config
<field fieldName="color_sm"
type="Sitecore.XA.Foundation.Search.ComputedFields.ResolvedLinks, Sitecore.XA.Foundation.Search" referenceField="Color" contentField="color"/>
This is my fruit template:
This is my color template:
Facet details
This is my dropdown filter:
This is the result i am getting now:
2nd round workaround
Fruit template
Color template:
Facet details:
Colors:
Config change:
<field fieldName="colortext" type="Sitecore.XA.Foundation.Search.ComputedFields.ResolvedLinks, Sitecore.XA.Foundation.Search"
referenceField="color" contentField="Color"/>
Current result:
After removing the fields from the template i m getting the below result:
Solr Data:
Can anyone please help how can i achieve the chinese data under my dropdown.
Thanks
| |
You'll need to subscribe to the GeoLocation service if you haven't yet. You can do this through the self-service portal which you can find at https://support.sitecore.net. See here for more details on signing up for the service.
If you've subscribed you also need to activate the IP Geolocation service through configurations. You can do this be setting the value GeoIp.PerformLookup to true in webroot\App_Config\Sitecore\DetectionServices.Location\Sitecore.CES.GeoIp.config.
More information can be found here.
|
How to get user's geolocation
Using Sitecore 10.1
Xdb.Enabled & Xdb.Tracking.Enabled values are set to true and the layout file has - @Html.Sitecore.VisitorIdentification().
The following values are null.
var country = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Country;
var city = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.City;
var latitude = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Latitude;
var longitude = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Longitude;
I'm assuming, Geolocation services are a part of this version. right?
If yes, is there any config setting to change, to fetch the above values?
| |
Create API on top of Sitecore based on WebAPI and create a method that would process your call. Probably work for Sitecore Backend developer. You would just send request with all form params to this method and then save them in Sitecore. Don't forget about encoding/decoding form field values so nobody uses this gate to inject malformed and protentional risky content.
Another option would be to use Sitecore Forms -> https://jss.sitecore.com/docs/techniques/forms.
|
Submit data from contact-us form and saving it to Sitecore using sitecore JSS - Angular App
I am using Sitecore 10 with JSS - Angular App, I have a contact-us form in page and I need to submit the data of form and save it to Sitecore tree.
What is the best solution to do this?
| |
If you want control over the markup using C# then you can try something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<renderField>
<processor
patch:instead="processor[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']"
type="Company.Foundation.Media.Pipelines.RenderField.GetImageFieldValue, Scms.Foundation.Media" />
</renderField>
</pipelines>
</sitecore>
</configuration>
using Sitecore.Diagnostics;
using Sitecore.Pipelines.RenderField;
namespace Company.Foundation.Media.Pipelines.RenderField
{
public class GetImageFieldValue : Sitecore.Pipelines.RenderField.GetImageFieldValue
{
public override void Process(RenderFieldArgs args)
{
Assert.ArgumentNotNull((object)args, nameof(args));
if (!this.IsImage(args))
{
return;
}
var renderer = new ImageRendererEx();
this.ConfigureRenderer(args, renderer);
this.SetRenderFieldResult(renderer.Render(), args);
}
}
}
using System.IO;
using System.Text;
using System.Xml.Linq;
using Sitecore;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Xml.Xsl;
namespace Company.Foundation.Media.Pipelines.RenderField
{
public class ImageRendererEx : ImageRenderer
{
public override RenderFieldResult Render()
{
var obj = Item;
if (obj == null)
{
return RenderFieldResult.Empty;
}
var attributes = Parameters;
if (attributes == null)
{
return RenderFieldResult.Empty;
}
var width = MainUtil.GetInt(Extract(attributes, "width", "w"), 0);
var height = MainUtil.GetInt(Extract(attributes, "height", "h"), 0);
var scale = MainUtil.GetFloat(Extract(attributes, "scale", "sc"), 0.0f);
var maxWidth = MainUtil.GetInt(Extract(attributes, "maxWidth", "mw"), 0);
var maxHeight = MainUtil.GetInt(Extract(attributes, "maxHeight", "mh"), 0);
var innerField = obj.Fields[FieldName];
if (innerField == null) return base.Render();
var imageField = new ImageField(innerField, FieldValue);
ParseField(imageField);
AdjustImageSize(imageField, scale, maxWidth, maxHeight, ref width, ref height);
if (imageField.MediaItem == null) return base.Render();
var imageMediaItem = new MediaItem(imageField.MediaItem);
if (imageMediaItem.MimeType == "image/svg+xml")
{
return new RenderFieldResult(RenderSvgImage(imageMediaItem, width, height));
}
return base.Render();
}
private string RenderSvgImage(MediaItem mediaItem, int width, int height)
{
Assert.ArgumentNotNull(mediaItem, nameof(mediaItem));
string result;
using (var reader = new StreamReader(mediaItem.GetMediaStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
var svg = XDocument.Parse(result);
if (svg.Document?.Root == null) return result;
if (width > 0)
{
svg.Document.Root.SetAttributeValue("width", width);
}
if (height > 0)
{
svg.Document.Root.SetAttributeValue("height", height);
}
result = svg.ToString();
return result;
}
}
}
Comments: If you really want to be fancy you can use similar code but turn it into a Scriban function.
|
How do you render an svg element with the SXA rendering variants?
I need to render a image in SVG format on my site. I want to create another rendering variant of the SXA Image Rendering Variant, so that the image is rendered as SVG.
With the current Image Rendering Variant renders image as
<a title="LW Logo Image Link" href="/"><img src="/-/media/Project/LW/LW/logo-lmage.svg?iar=0&amp;hash=F9D590BA05C61D36E9D5808F830D3D29" alt="" data-variantitemid="{F10CA728-FEDA-4706-B8D6-1651842E4BBA}" data-variantfieldname="Image"></a>
I want the new variant to render the image as
<svg role="img" focusable="false" aria-hidden="true" xmlns="http://www.w3.org/2000/svg"width="500"height="40" viewBox="0 0 500 40" overflow="visible"><path d="M489 26.8v-5.5h2.2c3........."></path></g></svg>
Can this be done with creating a new Rendering variant or do I need to create a custom SXA component?
| |
Based on the definition of Range Slider SXA component this is not possible:
Because these values need to be numeric. Picture taken from official SXA documentation -> https://doc.sitecore.com/users/sxa/93/sitecore-experience-accelerator/en/use-the-sxa-search-filter-components.html.
However, you could clone the component and try to change "backend" implementation of Controller to your needs to calculate it from SOLR values coming as output.
|
Range slider filter without minimum/maximum values
I have added a custom field in Solr beds and created a new Bedrooms facet. I am using the facets in a Range Slider Filter
I have defined the minimum and maximum values. Is there a way we should not define the minimum and maximum values and uses the original minimun/maximum bedrooms values in the index? I don't want to hard-code the minimum/maximum values because I don't know the minimum/maximum bedroom values in the indexes.
Is this possible to do?
Thanks in advance
| |
You can change the components that are added on the Review tab if you open the Presentation details in the core database on the item /sitecore/client/Applications/ECM/Pages/Messages/Regular/PageSettings/Tabs/Review/SubTabs/SendQuickTest.
You can add new components to the Layout similar to how the Textbox component is added.
If you open the details you will see that an ID was specified for the textbox:
This ID is used in the \sitecore\shell\client\Applications\ECM\EmailCampaign.Client\Pages\Tabs\40-Review.js and \sitecore\shell\client\Applications\ECM\EmailCampaign.Client\Component\Tab\ReviewTab.js which send the textbox value when the button was submitted and also control the way the components are displayed in the tab.
When submitting the form the values are passed as a model to the ExecuteSendQuickTest(SendQuickTestContext data) action from the ExecuteSendQuickTestController (you can see the implementation in the Sitecore.EmailCampaign.Server.Controllers.SendQuickTest.ExecuteSendQuickTestController class).
The model is defined in the Sitecore.EmailCampaign.Server.Contexts:
public class SendQuickTestContext : MessageContext
{
[JsonProperty("testEmails")]
public string TestEmails { get; set; }
[JsonProperty("variantIds")]
public string[] VariantIds { get; set; }
}
That specific Quick Test popup dialog is not possible to be changed as everything is hardcoded in the \sitecore\shell\client\Applications\ECM\main.7d48bdcafd27fc1376be.bundle.js. The only thing that you can change would be the translations for the elements which you can change on /sitecore/client/Applications/ECM/Translations/Enter the email that you want to send quick test to.
|
Custom EXM UI on Sitecore 9.3
I am using Sitecore 9.3.
I want to add one custom field on the review tab when sending a quick test email for EXM but can't find where source code to customize that. I saw that all UI is bin to minimize js file without source code.
Any suggestion about that?
| |
You need to follow the upgrade guide that you can download from https://dev.sitecore.net/Downloads/Sitecore_Experience_Platform/93/Sitecore_Experience_Platform_93_Initial_Release.aspx
Also after doing a database upgrade, you need to follow Install the Upgrade package then Configure Sitecore and so on to have the upgraded version 9.3.
You need to download below from the above url.
Also, another approach is by following How to do a data migration from 8.2 to 9.3
Set up a blank version of your starting environment (8.2 for you) and attach your core/master databases. In your case, since you have custom tables in the core db, you might want to back those up and then drop them before the upgrade. I'd also consider just running them out of a separate database, but I don't know your specifics with them.
Run the upgrade from 8.2 to 9.3; this will upgrade your databases as well.
Install a clean 9.3 environment, replace the core/master databases there with the upgraded ones.
Upgrade your code, etc, and hook everything up to your new environment.
|
Sitecore 8.2 to 9.3 Upgrade the databases approach
We are planning to upgrade from Sitecore 8.2 update 2 to 9.3. Customer suggests to follow DB upgrade approach. I have followed the below steps to upgrade the databases as per sitecore upgrade approach doc but nothing changed in Sitecore interfaces after run the below scripts and also didn't get any error. Do i need to follow any other steps to upgrade the databases apart from the 2 scripts
To upgrade the databases:
Extracted the database upgrade scripts from the Database Upgrade Script.zip file
Executed the below script individually in top of sitecore 8.2 core database, master database and web database
CMS_core_master_web8x.sql
Executed the below script in top of Sitecore 8.2 core database
CMS_core.sql
I would like to know anyone has worked on a similar migration. Thanks in advance
| |
If you are referring to the cookies that sitecore is using, you can take a look at the documentation to see the full list of cookies https://doc.sitecore.com/developers/93/platform-administration-and-architecture/en/cookies-used-by-sitecore.html. Then in your code you would just handle the rest.
If you need to handle the case where custom cookies might be added in other pipelines, you could implement your own pipeline and have it registered before the custom ones, for example if you take a look at the sitecore pipeline:
<httpRequestBegin>
<processor type="Sitecore.Pipelines.PreprocessRequest.CheckIgnoreFlag, Sitecore.Kernel"/>
<processor type="Sitecore.Pipelines.HttpRequest.EnsureServerUrl, Sitecore.Kernel"/>
<processor type="Sitecore.Pipelines.HttpRequest.StartMeasurements, Sitecore.Kernel"/>
<processor type="Sitecore.Analytics.Pipelines.HttpRequest.StartDiagnostics,Sitecore.Analytics" patch:source="Sitecore.Analytics.Tracking.config"/>
....
<httpRequestBegin>
You would register your custom processor like this:
<pipelines>
<httpRequestBegin>
<processor patch:before="processor[@type='Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel']" type="YourNamespace.CustomProcessor, YourProject" />
</httpRequestBegin>
</pipelines>
|
How to check if a cookie is sent by the browser or added in Sitecore pipelines?
If a cookie is added in any of the sitecore pipelines, it will already be in HttpContext.Current.Request.Cookies in the next pipeline.
I have to check if the browser sent any cookies, but because of this I can't use HttpContext.Current.Request.Cookies as I can't be sure if a cookie in it was sent by the browser or added by code. Is there any solution to this?
When adding cookies in code:
HttpContext.Current.Response.Cookies.Add(cookie);
When reading cookies in other pipelines for the same request:
HttpContext.Current.Request.Cookies.Get(name);
| |
You can achieve this by writing a Powershell script - https://michaellwest.blogspot.com/2014/10/sitecore-powershell-extensions-tip.html?_sm_au_=iVVB4RsPtStf5MfN
Below PowerShell script is for finding media items without reference to any other item. Please have a look.
<#
.SYNOPSIS
Lists all media items that are not linked to other items.
.NOTES
Michael West
#>
# HasReference determines if the specified item is referenced by any other item.
function HasReference {
param(
$Item
)
$linkDb = [Sitecore.Globals]::LinkDatabase
$linkDb.GetReferrerCount($Item) -gt 0
}
<#
Get-MediaItemWithNoReference gets all the items in the media library
and checks to see if they have references. Each item that does not
have a reference is passed down the PowerShell pipeline.
#>
function Get-MediaItemWithNoReference {
$items = Get-ChildItem -Path "master:\sitecore\media library" -Recurse |
Where-Object { $_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder }
foreach($item in $items) {
if(!(HasReference($item))) {
$item
}
}
}
# Setup a hashtable to make a more readable script.
$props = @{
InfoTitle = "Unused media items"
InfoDescription = "Lists all media items that are not linked to other items."
PageSize = 25
}
# Passing a hashtable to a command is called splatting. Call Show-ListView to produce
# a table with the results.
Get-MediaItemWithNoReference |
Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} },
@{Label="Path"; Expression={$_.ItemPath} }
Close-Window
|
How to find unused images /files in the media library and clean them up?
We have been using Sitecore as CMS for quite some time. We would like to clean up the images and files which are not linked with any items and archive them.
Is there any approach you have used for this ? Please let us know.
| |
Take a look on the original View for OOTB Video component located under $path_to_sitecore_instance$\Views\Video\Video.cshtml:
Copy those 3 highlighted lines either for Caption or Description fields:
<div class="video-caption">
@Html.Sxa().Field("MovieCaption", Model.DataSourceItem, Model.GetRenderingWebEditingParams())
</div>
Change the definition of which field to change:
@Html.Sxa().Field("MovieCaption", Model.DataSourceItem, Model.GetRenderingWebEditingParams()) to your desired by replacing "MovieCaption" with "My-custom-field-name"
Don't forget not to do this in OOTB Video View cshtml file. But create your own by copying the original cshtml file, make above changes and then set Rendering View Path on your custom Video component (cloned from OOTB one):
|
How to make a Custom field to be Editable from Experience Editor in Sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7. We have a requirement for video component with some extra fields so I have cloned the existing video component and added a custom field for it and I want to show that custom field in the Experience Editor like MovieCaption and MovieDescription which is shown in existing SXA video component.
I want to show my custom field along with those 2 text editor options.
Can anyone please help how can i achieve that?
Thanks
| |
This looks similar to the issue we had in our solution which was identified as a bug in Layout Service and fixed for us by Sitecore Support in both 9.3 and 10.0.
You can check it with Sitecore Support with reference number: 442855 (CS0196105)
Issue.
Description: LayoutService renders item fields without Values after reaching max depth for all the subsequent items\fields.
Reference: https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1000593
|
Why JSS Layout Service default resolver differently resolves reference fields of the same item, leaving some with the reference item context or ID?
JSS Layout Service default resolver resolves reference fields with full referenced item context, but other reference fields leaves with the ID of the referenced item.
For example there is an item, that has two fields of the same type that references other item by ID (multilist, droplink...). If this item is used by itself in the datasource and has no child items, then json rendering is processed correctly and Layout Service api returns this item with the fields, where referenced items are replaced with the context of those items.
However if those fields reference similar items with similar structure of reference fields, that also references other items even deeper in the tree, then some fields are resolved by the referenced item context, but some left as IDs of the referenced item.
Item template:
Item structure, where "New Test 1" item will be a datasource for json rendering and all child items reference their child items:
Response from Layout Service API:
{
"uid": "1daec8dc-3068-48bc-a73a-1411d464fb5d",
"componentName": "Test Component",
"dataSource": "{20A06569-2FDB-4130-B9E7-4B6861682FAB}",
"params": {
},
"fields": {
"list1": [
{
"id": "7e47ccc1-ddf9-4967-ab80-a075dc53eb96",
"fields": {
"list1": [
{
"id": "e45adddc-75d5-43b6-aba6-d91d156f32a9",
"fields": {
"list1": [
],
"list2": [
]
}
}
],
"list2": [
{
"id": "e45adddc-75d5-43b6-aba6-d91d156f32a9",
"fields": {
"list1": [
],
"list2": [
]
}
}
]
}
}
],
"list2": "{7E47CCC1-DDF9-4967-AB80-A075DC53EB96}"
}
}
I would have expected field ""list2": "{7E47CCC1-DDF9-4967-AB80-A075DC53EB96}"" to be resolved the same as it is for list1.
Are there any configuration parameters for the rendering, that dictates how such fields should be resolved?
| |
I have fixed this myself by overriding the following:
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderSection
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderTitle
With this code:
protected override void GetAttributeTokenValues(
Item item,
IDictionary<string, string> attributes,
MatchCollection matches,
string value,
string key)
{
//this.GetAttributeTokenValues(item, attributes, (collection, k, v) => collection.Add(k, v), matches, value, key);
foreach (Match match in matches)
{
string attributeTokenValue = this.GetAttributeTokenValue(match.Groups[1].Value, item);
value = value.Replace(match.Value, attributeTokenValue);
if (attributes.ContainsKey(key))
{
attributes[key] = value;
}
else
{
attributes.Add(key, value);
}
}
}
I have raised this to sitecore support and they confirmed the issue with public ref 460090. As I have fixed this myself I didn't request a hotfix.
|
Is it possible to have more than one token field in a rendering variant?
In SXA 1.8 I had a rendering variant with a VariantSection, with a style key on the Data attributes field, with value of background-image:url($(PromoImage));background-position: $(Horizontal Focal Point) $(Vertical Focal Point);
This was working totally fine, but when upgrading to SXA 10.1.0 I now get this error:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +60
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +14338200
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderRenderingVariantFieldProcessor.GetAttributeTokenValues(Item item, T attributes, Action`3 collectionAction, MatchCollection matches, String value, String key) +326
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderRenderingVariantFieldProcessor.GetAttributeTokenValues(Item item, IDictionary`2 attributes, MatchCollection matches, String value, String key) +219
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderRenderingVariantFieldProcessor.GetVariantAttributes(RenderingVariantFieldBase variantField, Item item, Object model) +319
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderRenderingVariantFieldProcessor.AddWrapperDataAttributes(RenderingVariantFieldBase variantField, RenderVariantFieldArgs args, HtmlGenericControl tag) +49
Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField.RenderSection.RenderField(RenderVariantFieldArgs args) +699
Sitecore.XA.Foundation.Variants.Abstractions.Pipelines.RenderVariantField.RenderVariantFieldProcessor.Process(RenderVariantFieldArgs args) +138
If I change the field to only have one token in it, it works fine. It doesn't matter which token I keep. Why do multiple tokens now break it?
| |
The resource items that got introduced in 10.1 cannot be deleted. I would assume Sitecore had a reason to do so - those items are not in a database anymore but in a (resource) file so it's probably not such a good idea to edit those (as that is the whole point of the change - those files should not be edited).
You can make changes and those will be saved in the database, but there is no mechanism to delete them. And I guess this makes some sense, although I do understand your question as we were used to be able to do that.
But this brings me to a question about your security setup: why would you hide those from admins? People with admin rights see everything. If items from a marketing control panel don't make sense to someone, that person should not be an admin. So my suggestion for you is to actually rethink your security setup - editors should not be admins...
|
Is it possible to remove system items from Sitecore in 10.1+?
In Sitecore 10.1 the system items in core / master DB cannot be moved or deleted. It is possible to hide these from non-admin users with security, but is it possible to hide these from admin users? Or ideally delete them totally?
The use case here is items in Marketing Control Panel - there are a lot of stock items that don't make sense for the client.
| |
Try this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
<sitecore>
<services>
<register serviceType="Sitecore.XA.Foundation.Search.Services.ISearchService, Sitecore.XA.Foundation.Search" implementationType="Sitecore.XA.Foundation.Search.Services.SearchService, Sitecore.XA.Foundation.Search" lifetime="Singleton">
<patch:attribute name="implementationType">SearchFeatureCustomization.CustomSearchService, SearchFeatureCustomization</patch:attribute>
</register>
</services>
</sitecore>
</configuration>
|
Sitecore Patch not working in sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7 .I have overriden the ContentPredicate() method for chinese language search box drawback from Sitecore.XA.Foundation.Search.Services.SearchService and i want to apply a patch for it so i have created config file under App_Config/Include folder but this patch is not working.
If i directly edit the Sitecore.XA.Foundation.Search the overriden method is getting called and its working but when i try to apply a patch it is not.
Sitecore.XA.Foundation.Search file:
<register serviceType="Sitecore.XA.Foundation.Search.Services.ISearchService, Sitecore.XA.Foundation.Search" implementationType="Sitecore.XA.Foundation.Search.Services.SearchService, Sitecore.XA.Foundation.Search" lifetime="Singleton"/>
<!-- <register serviceType="Sitecore.XA.Foundation.Search.Services.ISearchService, Sitecore.XA.Foundation.Search" implementationType="SearchFeatureCustomization.CustomSearchService, SearchFeatureCustomization" lifetime="Singleton"/>-->
Here is my overriden code:
namespace SearchFeatureCustomization
{
public class CustomSearchService : Sitecore.XA.Foundation.Search.Services.SearchService
{
protected override Expression<Func<ContentPage, bool>> ContentPredicate(string content)
{
Expression<Func<ContentPage, bool>> expression = PredicateBuilder.True<ContentPage>();
if (string.IsNullOrWhiteSpace(content))
{
return expression;
}
foreach (string item in content.Split().TrimAndRemoveEmpty())
{
string t = item;
expression = expression.And((ContentPage i) => i.AggregatedContent.Contains(t) || i.AggregatedContent.Equals(t, StringComparison.InvariantCultureIgnoreCase));
}
return expression;
}
}
}
This is my patch file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<services>
<pipelines>
<initialize>
<register type="SearchFeatureCustomization.CustomSearchService, SearchFeatureCustomization"
patch:before="processor[@type='Sitecore.XA.Foundation.Search.Services.ISearchService, Sitecore.XA.Foundation.Search']" lifetime="Singleton" resolve="true"/>
</initialize>
</pipelines>
</services>
</sitecore>
</configuration>
can anyone please help where i am going wrong.
Thanks
| |
If you are using the Publishing Service you can use the values that are shown on the Dashboard by accessing /sitecore/client/Applications/Publishing/Dashboard:
If you look at the Network tab you will see that it is doing a call to the API /sitecore/api/ssc/publishing/jobs/%7B00000000-0000-0000-0000-000000000000%7D/All?sourceDatabase=master. This basically retrieves a JSON with all the Jobs aswell as their statuses. The first part of the JSON looks like this:
{
"Messages": [],
"Active": [],
"Queued": [],
"Recent": [
{
"ManifestIdList": [
"39cbd98d-7abd-4c35-b152-6c18d7a81532"
],
"Type": {
"DisplayName": "Single Item"
},
"TypeDisplayName": "Item publish",
"ItemId": "{6bfa19da-4596-473d-8c78-0411cfd83799}",
"SourceDatabase": "master",
"ItemName": "CommonName6bfa19da-4596-473d-8c78-0411cfd83799",
"RequestedBy": "sitecore\\admin",
"Status": "Completed",
"StatusMessage": "OK",
"Languages": [
{
"Code": "en",
"DisplayName": "English"
}
],
You would use the "Status": "Completed" in your code to verify if the Job finished successfully. The same would apply to see if the Job is in Active, Queued or Recent.
|
Not able to get Publishing Status through PublishManager
I am using Publishing Service and tried to implement the Publish Manager API to retrieve Publish Status, but once the publishing is completed (successfully or unsuccessfully) the PublishManager.GetStatus(handle) returns null.
So, I am not able to actually get the exact status of publishing once its completed.
Below is the code that I tried to implement:
var handle = PublishManager.PublishItem(item, new[] { _webDb }, _webDb.Languages, true, false);
if (handle != null)
{
var publishStatus = PublishManager.GetStatus(handle);
if (publishStatus != null)
{
while (!publishStatus.IsDone)
{
Thread.Sleep(30000);
publishStatus = PublishManager.GetStatus(handle);
}
// Log the publishing status once its finished
Logger.Info("Publish Status: " + publishStatus.State);
Logger.Info("Publish Status : IsDone: " + publishStatus.IsDone);
Logger.Info("Publish Status : IsExpired: " + publishStatus.Expired);
Logger.Info("Publish Status : IsFailed: " + publishStatus.Failed);
}
}
Also I tried to implement below, but this also returns Publish Status as null
var handle = PublishManager.PublishItem(sitemapRoot, new[] { _webDb }, _webDb.Languages, true, false);
PublishManager.WaitFor(handle);
var publishStatus = PublishManager.GetStatus(handle);
Could there be any other way by which we can get the Publishing Status to know whether it was a success or failure?
| |
If it's purely presentational Dawid's answer in your link works perfect.
However, if you want to display other fields for example you might be able to work with the Rules engine:
Each individual field, section, Scriban etc. under the Variant Definition item has that field and can be utilized to make sure that does/doesn't render out depending on whether the rule evaluates to true or false. A step-by-step example of how you can use it can be found here.
I do believe you need to be using a reasonably new version of Sitecore/SXA (9.3 from the top of my head but I can be wrong)
edit
A very simple example of a custom rule to check whether the item is the first:
public class IsFirstItem<T> : WhenCondition<T> where T : RuleContext
{
protected override bool Execute(T ruleContext)
{
return ruleContext.Item.Parent.Children.First().ID == ruleContext.Item.ID;
}
}
You can then add a Condition item, for example here: /sitecore/system/Settings/Rules/Definitions/Elements/Item Hierarchy/your custom rule item
Set the Text field to something like 'where the item is the first child' and the Type to Namespace.Class.IsFirstItem,YourAssembly
|
How you render Page List data with multiple rendering variants?
I have a Query which returns a list of all "blog posts" sorted by date. I have a "Page List" variant-definition to display each blog post in the list, but how do I make the first returned blog post use a different variant-definition?
I have found another question which is maybe the same:
This answer for example
That is, do this by using CSS.
But what if I need to display extra data in the first result - for example I want to display the image for the first blog result, but not for the others? Do I "display" the image in the variant definition for all results, and use CSS to only show the image in the first result?
| |
I found a block named GetSellableItemsViewBlock in which it is fetching all the Sellable Items
await sellableItemsViewBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof (SellableItem), string.Format("{0}", (object) CommerceEntity.ListName<SellableItem>()), 0, int.MaxValue), context))?.List?.Items
So you can use the above code to get all the sellable items.
You can dotpeek into GetSellableItemsViewBlock class, it's in Sitecore.Commerce.Plugin.Catalog.dll
|
How to get sellable items from a catalog
I'm just getting started with Sitecore Commerce (10.1) and having a tough time trying to figure out things.
From the sample solution in the Sitecore.Commerce.Engine.SDK, I understood that we need to refer the Sitecore.Commerce.ServiceProxy project. But I'm unable to go any further.
The catalog will have around 8000 items and I would like to display them on the webpage.
Could anyone please help me with any pointers or the code on how to get the list of sellable items.
Basically, any documentation which is a step by step guide would be much helpful.
| |
The sitecore forms module doesn't support web forms, you will have to use MVC if you want to install and use it in your sitecore solution.
For sitecore 9.0 however you can still use the old web forms for marketers module https://dev.sitecore.net/Downloads/Web_Forms_For_Marketers.aspx, which works with web forms. You can take a look at the sitecore documentation https://doc.sitecore.com/developers/90/web-forms-for-marketers/en/insert-a-web-form-directly-on-a-web-page.html.
If you plan to use WFFM note that it works only until 9.0 as stated in the doc: Web Forms For Marketers was deprecated with the release of Sitecore XP 9.1. You will also have problems when doing the upgrade as OOTB is not supported and you'll have to use a custom tool to migrate data from WFFM to Forms, as answered here Migrating WFFM to Sitecore 9 Forms Module.
|
Sitecore Forms with User Control(.ascx)
Currently using Sitecore 9.0.1 and want to use Sitecore Forms module. Is there a way to use Sitecore Forms using User Control(.ascx)?
Tried using MVC https://doc.sitecore.com/developers/93/sitecore-experience-manager/en/add-a-form-to-a-webpage.html and it's working. But there is no documentation for user control (Sublayouts - .ascx).
| |
That issue will occur if there is a reference from a media item "blob" field to a missing blob in the "Blobs" table.
It might be that the UpgradeApp.exe tool wasn't able to clean up some system media files correctly.
You can run this SQL to find such fields:
select itemid
FROM [dbo].[SharedFields] s
left join [dbo].[Blobs] b on s.value = '{' + cast(b.BlobId as varchar(36)) + '}'
where s.fieldid = '{40E50ED9-BA07-4702-992E-A912738D32DC}' and blobid is null
And then you can verify them and then safely delete out those SharedFields from the database.
You can also check the versioned blob fields in case you are using versioned media items
select itemid
FROM [dbo].[Fields] s
left join [dbo].[Blobs] b on s.value = '{' + cast(b.BlobId as varchar(36)) + '}'
where s.fieldid = '{DBBE7D99-1388-4357-BB34-AD71EDF18ED3}' and blobid is null
|
Publishing error BlobProviderException: No supported provider for is configured
I hit this on a Sitecore 10.1 upgrade when trying to publish
Sitecore.Framework.Data.Blobs.Abstractions.BlobProviderException: No supported provider for is configured.
at Sitecore.Framework.Data.Blobs.BlobStorage.GetBlobProvider[T](BlobIdentifier identifier)
at Sitecore.Publishing.PublishHelper.CopyBlobField(Field sourceField, Item targetVersion)
at Sitecore.Publishing.PublishHelper.CopyBlobFields(Item sourceVersion, Item targetVersion)
at Sitecore.Publishing.PublishHelper.TransformToTargetVersion(Item sourceVersion)
at Sitecore.Publishing.PublishHelper.CopyToTarget(Item sourceVersion, Item originalItem)
at Sitecore.Publishing.PublishHelper.PublishVersionToTarget(Item sourceVersion, Item targetItem, Boolean targetCreated)
at Sitecore.Publishing.PublishHelper.PublishVersion(Item sourceVersion)
at Sitecore.Publishing.Pipelines.PublishItem.PerformAction.Process(PublishItemContext context)
I have run the UpgradeApp.exe tool as per the upgrade guide.
What else am I missing?
| |
I've talked to the Sitecore Service and this is not a bug that the useDisplayName is not working, its just like it is in 9.3.
But I got a code snipped I am currently trying the following Code to solve my problem:
public class CustomMediaProvider : MediaProvider
{
public override string GetMediaUrl(MediaItem item, MediaUrlBuilderOptions options)
{
try
{
if (Context.PageMode.IsNormal)
{
string url = base.GetMediaUrl(item, options);
string displayName = options.LowercaseUrls == true
? MainUtil.EncodeName(item.DisplayName.ToLower())
: MainUtil.EncodeName(item.DisplayName);
string itemName = options.LowercaseUrls == true
? MainUtil.EncodeName(item.Name.ToLower())
: MainUtil.EncodeName(item.Name);
string extension = WebUtil.SafeEncode(StringUtil.EnsurePrefix('.',
StringUtil.GetString(options.RequestExtension, item.Extension, "ashx")));
if (!string.IsNullOrEmpty(displayName) && url.Contains(itemName + extension))
{
url = url.Replace(itemName + extension, displayName + extension);
}
return url;
}
}
catch (Exception exception)
{
Log.Error($"Fehler beim CustomMediaProvider für das Item mit der id: {item.ID}", exception, typeof(Exception));
}
return base.GetMediaUrl(item, options);
}
}
and I've registered this
<mediaLibrary>
<mediaProvider>
<patch:attribute name="type">NamespaceTo.CustomMediaProvider, Sales.Test.Feature.Media</patch:attribute>
</mediaProvider>
</mediaLibrary>
|
Sitecore 9.3 Render MediaUrls by displayname with UseDisplayName from MediaUrlBuilderOptions
I have a multilanguage setup in my sitecore instance and we are using the displayname for default URLs that works great. But we also want that the media Item (images) to show up translated in the HTML.
That was working in 9.0.2 with this Implementation => Render image with display name by default
But after upgrading my current system to Sitecore 9.3 this is not working anymore. I was hoping that the new option
var options = MediaUrlBuilderOptions.Empty;
options.UseDisplayName = true;
var url = MediaManager.GetMediaUrl(imageField.MediaItem, options)
is working as the name says UseDisplayName but this seems not to work. Are there some other options to get this working in sitecore 9.3?
| |
To translate Forms error messages you need two translations: one for the front-end messages (javascript) and one for the back-end messages from Sitecore.
I think you already have the FE covered by following that other SSE answer (https://sitecore.stackexchange.com/a/18075/237) which directs you to my blog post on the subject: https://ggullentops.blogspot.com/2019/04/sitecore-9-forms-translating-client-error.html.
From your screenshot I think your main issue is the required fields. And that is indeed a special one. It's covered in my other post on translating error messages: https://ggullentops.blogspot.com/2017/10/sitecore-9-forms-translating-error.html
The code for the required field validation works in a different way
and the message will come from the Sitecore dictionary. If you want to
update or translate it, you need to add a key to that Dictionary. This
can be done in the master database - just add an item in the
/system/Dictionary - the name doesn't really matter. The key however
needs to be exactly "{0} is required.". The phrase can be anything you
want, just remember to add the {0} token. Translate and publish...
|
How to display the custom error message for the fields in Sitecore Form for Chinese language
I am using Sitecore 9.0.1 and I have created a Sitecore Form (not WFFM). I want to add a custom error messages to the fields. Below are the steps which I followed to add error message for Email:
1.created a custom validator called Email Validation here: /sitecore/system/Settings/Forms/Validations/Email Validation
Selected the newly created validation here: /sitecore/system/Settings/Forms/Field Types/Basic/Email
3.Under the Form field "Email" I changed the validator to "Email validation"
But still I am able to see the default English error message.
So I followed this other answer https://sitecore.stackexchange.com/questions/17905/sitecore-forms-email-field-validation-message-is-showing-in-english-instead-of-k and downloaded the zip file and placed it in my Sitecore instance \sitecore modules\Web\ExperienceForms\scripts folder and added the script under my Renderbody() and reverted my changes and made my form to use email validator but still I'm getting the same English error message for other fields but some different error for email field.
@using Sitecore.Mvc
@using Sitecore.ExperienceForms.Mvc.Html
@using Sitecore.Mvc.Analytics.Extensions
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="~/Assets/Form.css" />
<title>@Html.Sitecore().Field("title", new { DisableWebEdit = true })</title>
@Html.Sitecore().VisitorIdentification()
@Html.RenderFormStyles()
@Html.RenderFormScripts()
</head>
<body>
@RenderBody()
<script type="text/javascript">
var lang = '@Sitecore.Context.Language.Name';
var script = document.createElement("script");
if (lang == 'zh-cn')
{
script.src = "/sitecoremodules/Web/ExperienceForms/scripts/localization/messages_zh.js";
$("head").append(script);
}
</script>
</body>
</html>
Can anyone please guide where I am going wrong?
Thanks
| |
One possible approach is to use a Promo component. There are several benefits to cloning the component but that requires discussion beyond the scope of this answer.
In the example image provided you would need these fields:
Image
Title - single line text
Text - rich text
Link - one more general links
Next create a rendering variant like the following:
The rest would be using CSS to properly position the image on the left and the content on the right.
There are numerous designs you can achieve with this approach. Here are a few more examples:
By throwing in a VariantPlaceholder you can add components into same promo (such as seen here).
Here we are using the placeholder to render a Page List.
|
How do you create a promo with title, text, buttons, and image?
I received a requirement to show title, text, 1-3 buttons, and an image.
What is a possible way to produce something like the following?
| |
Unblock your file.
Locate the blocked file (your chf/chm file)
Right-click on the file and select Properties from the menu.
Click Unblock on the General tab.
Click OK.
Source: https://thirtysix.zendesk.com/hc/en-us/articles/202921675-How-to-Unblock-a-File-Downloaded-from-an-Email-or-the-Internet
|
Sitecore Commerce Documetation 10.1 is not working
I have opened the Sitecore.Experience.Commerce.SDK.Documentation.chm that comes with the XC 10.1 installation.
It shows no content for any of the nodes. Could this be a bug.
| |
For Azure PaaS infrastructure:
Looking at the Azure AppServices packages for a scaled XP solution, you will find that that the following three workers are deployed in their correlated app services and they are configured to run as Azure WebJobs.
xConnect Search Indexer - It runs as Azure WebJob in the xConnect Collection Search app service.
Marketing Automation Engine Worker - It runs as Azure WebJob in the Marketing Automation Operations app service.
Cortex Processing Engine Worker - It runs as Azure WebJob in the Cortex Processing app service.
You can explore the defined WebJobs of an app service in the Azure Portal, accessing the WebJobs section in the Settings area on the left navigation.
For Kubernetes infrastructure:
Each worker service container runs in its own independent single-container pod in a Kubernetes cluster.
Mapping of Docker Containers & Azure App Services:
The table below shows the potential mapping from a file system perspective of Docker containers and Azure App Services for a Sitecore XP scaled topology:
Docker Container
Azure App Service
cortexprocessingcortexprocessingworker
cortexprc
cortexreporting
cortexrep
xdbautomationxdbautomationworker
maops
xdbautomationrpt
marep
xdbcollection
xccollect
xdbrefdata
xcref
xdbsearchxdbsearchworker
xcsearch
|
How do the xConnect Docker containers correspond to the Azure xConnect app services?
I've tried to find documentation on the various xConnect roles that exist and their names and map them to the names of the xConnect containers in an XP1 container setup and an Azure PaaS configuration, but I'm not confident that I've got the mapping right.
I reviewed this documentation from Sitecore on the topic, but it contains yet a third convention of naming.
How do the following roles map up between the different infrastructure platforms?
Docker containers
This list is taken from the Sitecore docker examples repo
cortexprocessing
cortexprocessingworker
cortexreporting
xdbautomation
xdbautomationrpt
xdbautomationworker
xdbcollection
xdbrefdata
xdbsearch
xdbsearchworker
Azure PaaS
cortexprc
cortexrep
maops
marep
ops
xccollect
xcref
xcsearch
It looks like some of these are doubled up. Perhaps the workers are consolidated (e.g. cortexprocessing + cortexprocessingworker = cortexprc)?
| |
In 9.x Tracker.Current.Contact.Identifiers.AuthenticationLevel is gone. You only have known and unknown for each identifier you assign to a contact. If you still want to know if they were password validated vs not, then I would create a custom contact facet and put that information in there.
Also, identifying a contact is now done like the code below. This allows you to have multiple identifiers on a contact. Instead of the one identifier in 8.2
Tracker.Current.Session.IdentifyAs("emailaddress", email.ToLower());
|
Sitecore analytics upgrade code issue Sitecore 9.3
I am upgrading Sitecore 8.2 to Sitecore 9.3. While upgrading Sitecore.analytics reference to target version 9.3, I'm getting error on below code.
Getting Error in the below code
Error message "does not contain a definition for AuthenticationLevel."
Tracker.Current.Contact.Identifiers.AuthenticationLevel = AuthenticationLevel.PasswordValidated;
Tracker.Current.Session.Identify(contactIdentifier);
Full Code here
public void StartTracking(global::Sitecore.Security.Accounts.User user)
{
if (user == null)
return;
if (!Tracker.IsActive)
{
Tracker.StartTracking();
}
IdentifyContact(user);
}
public Contact IdentifyContact(global::Sitecore.Security.Accounts.User user)
{
if (user == null)
return null;
string contactIdentifier = GetContactIdentifier(user);
if (string.IsNullOrEmpty(contactIdentifier) || contactIdentifier.Contains("anonymous") || Tracker.Current == null || Tracker.Current.Session == null)
{
return null;
}
Tracker.Current.Contact.Identifiers.AuthenticationLevel = AuthenticationLevel.PasswordValidated;
Tracker.Current.Session.Identify(contactIdentifier);
return Tracker.Current.Contact;
}
How can we replace AuthenticationLevel in Sitecore 9.3 analytics ?
Anyone help on this issue
| |
You have to change property type from bool? to bool:
public bool PropertyDetailsInOffer { get; set; }
bool values will be rendered as checkboxes for supported UI Hints, otherwise rendering as a string value.
|
Checkbox showing on Bizfx but not in Sitecore
I am able to see Checkbox on Bizfx but when I do the Update Data Templates in Sitecore then its showing Single-Line Text rather than a Checkbox
This is the code to add a property. I have declared it as a bool
In the Bizfx when I open the field for the first time then it shows the field as the textbox
After entering true or false, then saving the field and opening it again shows the checkbox
But in Sitecore it always displays single-line text. I have run Delete Data Templates and Update Date Templates but it always shows the single-line text
Has anyone experienced the same thing and how to resolve this?
Any help or suggestion would be appreciated
Thanks in advance
| |
Issue is resolved by removing extra slash to the domain in AllowedOrigins.
|
The requested resource does not support http method 'GET'
When I open the Experience Profile tab on my Sitecore 9.1.1, I get an error: An error has occurred.
In Chrome console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) --/sitecore/api/ao/v1/contacts/search?&pageSize=20&pageNumber=1&sort=visitCount%20desc&Match=*&FromDate=null&ToDate=null:1
On opening that api uri, getting '{"Message":"The requested resource does not support http method 'GET'."}'
Verified XConnect running, solr url without # and Newtonsoft.Json.dll version.
| |
Make sure you're following all the below steps to add a form to a page::
Open the Toolbox. In the Forms section, select and drag the Sitecore Form Wrapper rendering to the relevant placeholder.
After that, drag an Mvc Form rendering to the Sitecore Forms Wrapper.
After dragging the Mvc Form onto the page, In the Select the Associated Content dialog box, select the form that you want to display on the page and click OK. The form is now displayed on the page.
In the Experience Editor, click Partial Design and click Metadata. In the SXA Toolbox, in the Forms category, drag and drop the Forms Scripts component before the closing /body tag of the page.
|
Sitecore Forms not taking Page design in Sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7 and I have created a form using Sitecore Forms and attached that form to a page through CMS and for the page I have assigned my Page design to it but it is not showing my header and footer design which is there in my page design.
Below are the steps which i followed to add my form to page:
1.Created a landing page and through presentation details i added my form to the page.
with the placeholders as "mainn" specified in my VS layout.
2.Same placeholder i have created under my Placeholdersettings
3.For the landing page i assigned my page design under page design section
This is the result I am getting: without page design:
I created one more page and added this rendering through experience editor there I am able to see my page design (header and footer) but on click on form submit it is redirecting to some formid URL and extra added sxa components are also not visible
Result what I am getting when I click submit button:
Url which it is redirecting to "sitecore901.local/formbuilder?fxb.FormItemId=8516cac6-205f-4040-9540-4fd1d787355e&fxb.HtmlPrefix=fxb.513f7c6f-97ac-4f24-8258-6fa184628d02 " and other sxa components added are also not showing up.
Workaround :
Added sitecore form wrapper and inside this i added the MVC form and specified the datasource form is also appearing on the page and its not redirecting and the placeholder for form is changed to this "/main/container-1/sitecoreFormsWrapper-1"(if i change it to "mainn" i am not able to see my page design so i have kept as it is) .But the sitecore form validations which i have applied for chinese is not working.
I specified the script in my VS under Renderbody() function of form
The result what i am getting now is:
I tried specifying that script file under script field of form but still the same issue.
Can anyone please help what needs to be done here?
| |
Solution 1 :
You can create a constructor and then find it from there as follows -
public IStorefrontContext StorefrontContext { get; set; }
public ISearchManager SearchManager { get; set; }
public YourController(IStorefrontContext storefrontContext, ISearchManager searchManager)
{
this.StorefrontContext = storefrontContext;
this.SearchManager = searchManager;
}
Then you can use your above code as -
SearchRepository searchRepository = new SearchRepository(this.SearchManager, this.StorefrontContext);
searchRepository.SearchCatalogItemsByKeyword("mdn","Brand", 10);
Solution 2 :
If you want to use your code as is then add reference of Microsoft.Extensions.DependencyInjection.Abstractions.dll in your solution and use
using Microsoft.Extensions.DependencyInjection; in your class
EDIT : If you haven't added your controller in config then need to add it as below. Create a patch file and add below lines -
<services>
<register
serviceType="abc.Feature.Catalog.Controllers.YourController, abc.Feature.Catalog"
implementationType="abc.Feature.Catalog.Controllers.YourController, abc.Feature.Catalog"
lifetime="Transient" />
</services>
|
How to get Storefrontcontext in XC 10.1
Using SC10.1 & XC 10.1
I'm trying to get catalog items with a search criteria.
The code in this Sitecore document to get the Storefrontcontext is not working.
var searchManager = CommerceTypeLoader.CreateInstance<ISearchManager>();
var storefrontContext = ServiceLocator.ServiceProvider.GetRequiredService<IStorefrontContext>();
SearchRepository searchRepository = new SearchRepository(searchManager, storefrontContext);
searchRepository.SearchCatalogItemsByKeyword("mdn","Brand", 10);
'IServiceProvider' does not contain a definition for
'GetRequestService' and no accessible extension method
'GetRequestService' accepting a first argument of type
'IServiceProvider' could be found.
| |
I have something that seems to solve this issue for me. Please comment if you have more info or insight about this.
It appears that Sitecore placeholders when generated are wrapped in a "div" with class "row".
For my installation using "bootstrap 4", this behaviour is defined in Sitecore at "/sitecore/system/Settings/Feature/Experience Accelerator/Bootstrap 4/Bootstrap 4 Grid Definition". See the "Placeholder Wrapper" section.
Part of the HTML generated by Sitecore for an overlay looks like this:
<span class="overlay-data" data-width="400" data-height="400" data-percent="">
<div class="row">
<div class="component container col-12"> <!-- component I added -->
Somehow the "row" here has margin-left and margin-right set to -15px.
The way I got around my issue was to upload an "extension" css file to "/sitecore/media library/Extension Themes/mysite/styles". In this css I redefined the margins for the row class used under the overlay placeholder:
span.overlay-data>.row {
margin-left: 0px;
margin-right: 0px;
}
|
SXA overlay opens with a scrollbar
Why does my overlay open with a horizontal scrollbar?
The only content in the "overlay" placeholder is an empty "Container". If I have no content whatsoever, then there is not scrollbar - but as soon as I add any content then I get the scrollbar.
EDIT: this seems to have something to do with the definition of the "row" css-class (which I think comes from "bootstrap"). This has "margin-left: -15px" for example. Any way to override this when defining the overlay?
EDIT: this is for Sitecore 10.1; SXA version 11200 (from "/sitecore/system/Settings/Foundation/Experience Accelerator/Upgrade/Current")
| |
Adding also an answer based on the comment that the field should be changed from DropList to DropLink. This is because DropList is storing the item names so the TargetItem value will be null, whereas DropLink is storing the Targeted Item's Guid and sitecore will retrieve the linked item.
You can verify the values aswell if checking the sitecore menu View -> Raw Values.
|
Sitecore not obtaining an item's fields
My sitecore Article Component is not picking up my authors details.
I have an Article component that has the path to my article html page, /Views/Basic Components/Article.cshtml.
In my author page Brendon Sanderson, which is under sitecore/content/home/Blog/, I selected the author Brendon Sanderson from the dropdown field in the edit menu. Therefore, the dropdown field is able to pick up all the authors under sitecore/content/Authors/
My question is why is my Article Component not displaying authorItems fields such as Profile Picture or Name?
| |
Integrating the SusyemSys.Saml2 into the identity server has some challenges. I ran into these same issues, but eventually got around them with some pain. Of course, there is a chance I some of the changes I made below could use some improvement, especially with respect to the updated dependencies.
You do need to include updated versions of Microsoft.IdentityModel.Tokens.Saml and Microsoft.IdentityModel.Xml assemblies.
Beyond that, you will also need to update your Sitecore.IdentityServer.Host.deps.json file to reflect the newer assembly versions.
In my case, I put my own identity server plugin, SysteamSys.Saml2.*, Newtonsoft.Json, Microsoft.Extensions.DependencyModel and System.configuration.ConfigurationManager assemblies at the root of the identity server directory.
Hope this helps!
|
Sitecore 10.0.1 Saml2 Federated Authentication using IdentityServer4 and SustainSys Microsoft.IdentityModel.Tokens.Saml.dll
We are attempting to set up a plugin for IdentityServer4 for Saml using SustainSys.Saml2. We are getting an error in the log files related to Microsoft.IdentityModel.Tokens.Saml.dll being missing. The file exists in the c:\Identity folder in the container because it is used by IdentityServer4. The version in SystainSys.Saml2 is newer than the version in the Sitecore IdentityServer4. Has anyone else run into this problem?
| |
I am able to resolve the issue by updating SXA SOLR index by adding following.
It seems single-line-text fields get stored as text_general so making it stored as a string brings back value as a whole and not separated by spaces.
<fieldTypes hint="raw:AddFieldByFieldName">
<field fieldName="blogauthor" returnType="string" />
</fieldTypes>
Thanks to Maarten from Sitecore slack community channel for suggestion.
|
SXA Dropdown Filter populates with words separated by space
Have a requirement to provide a filter on news articles for Author.
Created a dropdown filter based on a facet (which is based on a BlogAuthor template field which is of type single line text).
Now filter populates with author names separated out by spaces in them.
How can I populate filter with 'Author 1', 'Author 2' etc. I am using SOLR for search indexes.
| |
Yes, there is an embedded object called o_pagemode.
You can use this like o_pagemode.is_experience_editor in an if statement.
You can find all the options for the o_pagemode here: https://doc.sitecore.com/developers/sxa/101/sitecore-experience-accelerator/en/the-embedded-items-and-objects-in-the-scriban-context.html.
The following lists notable properties of the o_pagemode context object:
is_debugging: Indicates that the page is rendered in debug mode.
is_experience_editor: Indicates that the page is rendered within Experience Editor.
is_experience_editor_editing: Indicates that the page is rendered within Experience Editor in Edit mode.
is_normal: Indicates that the page is rendered for a visitor.
is_preview: Indicates that the page is rendered within Experience Editor in Preview mode.
is_simulated_device_previewing: Indicates that the page is rendered within Experience Editor in Simulated Preview mode.
is_profiling: Indicates that the page is rendered with profiling information.
Example:
{{ if (o_pagemode.is_experience_editor_editing) }}
<span>[Click here to edit the component]</span>
{{ else }}
... render the component here
{{ end }}
|
How do you detect Edit Mode in the Experience Editor with Scriban?
Is there a function that I can use in the Scriban template to implement conditional logic based on the fact that the page is opened in the Experience Editor?
Something like the below:
<div class="button--primary field-link">{{ sc_field item 'F1' }}</div>
{{ if is_editing }}
<div>{{ sc_field item 'F2' }}</div>
{{ end }}
| |
One option that could work is using Sitecore security. As each form element is an item in Sitecore, you can set security on it. If you deny read access to your logged-in users for the country item it will not be visible on the form. Other users that do have read access will still see the field.
|
Hide Sitecore Form fields if user is authenticated
Environment: Sitecore 9.2 & SXA 1.9
Scenario: I have created a Sitecore form, which consists of three fields and a submit button. Now I would like to hide one of the fields if the user is authenticated (extranet - logged in). Suppose, Form ABC has three Single-Line Text fields: Name, Contact, and Country. If the user is logged in then the Country field should not be visible to the user.
How to achieve this functionality? Thanks.
| |
It is not related to Sitecore link manager, there are many reasons and with some security reasons, browsers do not allow to load local resources, and anyway, it will run on the client-side, not on the server-side, where users can use the windows explorer. For your static HTML part, I guess you are running it from your local, not as a website and that's is the reason it is working for you but when you will host it will not work for the static HTML as well.
As per your comment - "This is an IntranetPortal and the client want to access a local drive from the portal." - if you add c:// in the link and somehow it works then also it will not complete your requirement because as I told you it will not run on the server-side and the end-user will see the local c drive of his, not the server where you hosted it.
|
File path not accessible from Sitecore link manager
Sitecore Version: 9.3 with SXA
We want to access the local file directory from the Link on the website. For that, we have entered, file directory path in Insert External Link.
After that, On the website, when we tried to click on the link, we are getting the error "Not allowed to load local resource":
But if we do the same thing in static HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample Code</title>
</head>
<body>
<h1>Opening a folder from HTML code</h1>
<a href="c://">
Click to open a folder
</a>
</body>
</html>
and click on the link, we are able to open the file directory.
Does anyone know the reason, why file paths are not accessible when the link is generated through the Sitecore link manager?
| |
You should think and understand the risks associated with such upgrade. What are the chances that there will be unexpected UI behaviors or JS errors from the upgrade? In my opinion, it is not safe to upgrade the jQuery for Sitecore, and below are a few points for this -
Sitecore is a very big system and it has lots of things dependent on the JQuery. If you are planning to upgrade the JQuery you need to test the full Sitecore system which is not an easy task.
You will never know the impact of it even after performing the complete testing.
When next time you will going to upgrade Sitecore, you will face similar problems with the new version of Sitecore.
It is not recommended to change anything on the existing Sitecore solution until there any specific requirement or the Sitecore team itself provided something to update.
Make sure you will have the Sitecore support continue after this jQuery upgrade.
Based on the security guidelines of some organizations, they don't allow the older version of jQuery for pubic facing websites but you can restrict the old JQuery access for the CD sites.
|
Upgrading jQuery for sitecore xp 9.3
I notice sitecore 9.3 does have a pretty low version of jQuery at several places in the content editor
in sitecore/shell/lib/jquery, ScriptResource.axd, Telerik.Web.UI.axd are all using jQuery 1.12.4
For the remaining areas, I have found information for upgrades but are the above stated jquery safe for updating?
| |
For sitecore 9.3 you need to change so that your custom processor inherits from InteractionAggregationPipelineProcessor from the Sitecore.Analytics.Aggregation namespace.
You can take a look at the sitecore documentation on how to create and use an interaction aggregation processor class https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/walkthrough--using-the-interactions-pipeline-to-aggregate-and-store-reporting-data.html#create-an-interaction-aggregation-processor-class_body
|
Upgrade for Sitecore Analytics in Aggregation
I am upgrading Sitecore 8.2 to Sitecore 9.3. While upgrading Sitecore.analytics.aggregation reference to target version 9.3, I'm getting the error The type or namespace 'AggregationProcessor' could not be found
for the code. And to upgrade the below custom processor, we need to get the visit details (args.context.visit.sitename and args.context.visit.pages) and it is not available in the 'InteractionAggregationPipelineArgs'. How could i use Interaction and Contact to get the visit details?
public class CentralLikeProcessor : AggregationProcessor
{
private Guid LikeEventDefinitionId = Common.Constants.PageEvents.Like.Guid;
protected override void OnProcess(AggregationPipelineArgs args)
{
Assert.ArgumentNotNull(args, "args");
Log.Info("xDB Started CentralLikeProcessor event", this);
if (args.Context.Visit.SiteName == "central" || args.Context.Visit.SiteName == "authoring")
{
if (args.Context.Visit.Pages == null)
{
return;
}
foreach (PageData page in args.Context.Visit.Pages)
{
if (page.PageEvents != null)
{
var fact = args.GetFact<CentralLikes>();
foreach (var pageEvent in page.PageEvents.Where(p => p.PageEventDefinitionId
== LikeEventDefinitionId))
{
var itemId = pageEvent.ItemId;
if (itemId != Guid.Empty)
{
var likeKey = new CentralLikeKey();
likeKey.ItemId = itemId;
var likeValue = new CentralLikeValue();
likeValue.Count = 1;
fact.Emit(likeKey, likeValue);
}
}
}
}
}
Log.Info("xDB Ended CentralLikeProcessor event", this);
}
}
}
Could you please suggest me on how to upgrade the above code with Sitecore 9.3?
| |
To fix the issue you need to implement React component for this rendering. The problem is that layout service returns it with space in name, so your componentFactory.js should have following generated output to register such component:
import HiddenRendering from '../helpers/HiddenRendering';
components.set('Hidden Rendering', HiddenRendering);
To achieve this modify generate-component-factory.js to:
return `/* eslint-disable */
// Do not edit this file, it is auto-generated at build time!
// See scripts/generate-component-factory.js to modify the generation of this file.
${imports.join('\n')}
import HiddenRendering from '../helpers/HiddenRendering'
const components = new Map();
${registrations.join('\n')}
components.set('Hidden Rendering', HiddenRendering);
export default function componentFactory(componentName) {
return components.get(componentName);
};
`;
Then implement HiddenRendering component in /src/helpers/HiddenRendering.js with some content authors friendly message. You don't need to check for normal/edit mode, cause component will appear only in Experience Editor edit mode:
import React from 'react';
const HiddenRendering = () => {
return (
<div>This component variant will be hidden in non-edit mode.</div>
);
};
export default HiddenRendering;
Note that component is implemented outside of /src/components folder for it not to be picked up by the generate-component-factory.js script as a normal component.
|
When JSS component is hidden via personalization Experience Editor show warning about missing "Hidden Rendering" implementation
After applying personalization rule to JSS component and using option to hide, Experience Editor shows warning that "Hidden Rendering" is not implemented in React, which is not too friendly for content authors.
This message appears only in Experience Editor editing mode. In non-edit mode layout service doesn't return the component at all and the issue doesn't exist.
| |
I ran into the same issue and resolved it by storing the IdToken in a persistent storage so it can be retrieved later during logout. In our case it is in Redis and we used the same approach as my answer here, but this can obviously be different depending on your solution. I'm assuming you have access to IdToken in SecurityTokenValidated event?
|
Using Okta OpenId Connect "A client_id must be provided in the request"
I am trying to use Sitecore 10.0.1, IdentityServer4, with Okta and OpenID Connect. When I click logout I get this error:
{"errorCode":"invalid_client","errorSummary":"A client_id must be provided in the request.","errorLink":"invalid_client","errorId":"oaevKZNtJFrRjqTZ_wCOsx6lA","errorCauses":[]}
Here is the OnRedirectToIdentityProviderForSignOut code:
options.Events.OnRedirectToIdentityProviderForSignOut += (Func<RedirectContext, Task>)(context =>
{
context.Request.QueryString.Add("client_id", identityProvider.ClientId); // Did not fix issue
context.Options.ClientId = identityProvider.ClientId; // Did not fix issue
context.Options.SignedOutRedirectUri = "https://id.myproject.localhost";
_logger.LogInformation("Redirect to identity provider for sign out. ClientId: {0}",
context?.Options?.ClientId);
context.ProtocolMessage.IdTokenHint = context.HttpContext.User.FindFirst("id_token")?.Value; // This returns null
_logger.LogInformation("IdTokenHint: {0}", context.ProtocolMessage.IdTokenHint);
return Task.CompletedTask;
});
options.Events.OnRedirectToIdentityProvider += (Func<RedirectContext, Task>)(context =>
{
_logger.LogInformation("Redirect to identity provider. IdToken: {0}.",
context.ProtocolMessage.IdToken);
var first = context.HttpContext.User.FindFirst("idp");
if (string.Equals(first?.Value, identityProvider.AuthenticationScheme, StringComparison.Ordinal))
context.ProtocolMessage.Prompt = "select_account";
return Task.CompletedTask;
});
I was thinking this might be related to IdTokenHint but I don't seem to have that available.
| |
As you can read on https://doc.sitecore.com/users/sxa/18/sitecore-experience-accelerator/en/walkthrough--adding-search-functionality-to-your-page.html the options for the suggestion mode are:
Show search results: shows the search results, rendered by rendering variants. User will be redirected to the clicked item.
Show predictions: shows search phrase predictions provided by the search engine. This mode is supported for Solr only.
Show search results as predictions: clicked text will be put in the search box and search is performed.
SXA uses a suggester called sxaSuggester. If you set up search
suggestions in Solr, make sure to use that name.
So in order to get the predictions working as you requested, you need to setup your solr to handle the suggestions. You can find some blogs on how to do that - one example is https://tamermblog.wordpress.com/2018/02/20/setting-up-sxa-search-box-with-suggest/.
|
SXA Search box is not showing Predictions for Chinese language in Sitecore 9.0.1
I am using Sitecore 9.0.1 with SXA 1.7 and Solr 6.6.2. I have added a search box component and search result component on the same page for a chinese language and also selected the ShowPrdeictions option for the search box but it is not working .
Here is the output of my page. When i search for some text it is not showing any suggestions
Can anyone please suggest if i am missing anything
Thanks
| |
A few things to consider when approaching this:
Where are the geo coordinates stored? Are the items in the content tree or somewhere else?
Does the bulleted list on the left match the items on the map?
Does the static map share the same API key used in the global map provider setting?
TIHIDI:
Items used to source the list and map inherit from the SXA POI template; this allows for storage of the latitude and longitude. /sitecore/templates/Foundation/Experience Accelerator/Geospatial/POI
The API key required for the static map was hardcoded in a Scriban rendering variant. A more ideal implementation would in some way extract the key from this item /sitecore/content/Tenant Folder/Tenant/Site/Settings/Maps Provider. Perhaps a Scriban function could be used to get the job done.
Assume a rendering variant configured like the following:
Google Maps Scriban Template
Assumes the items for the marker are children of the current page.
The map is hidden while in the Experience Editor.
{{
i_contextitem = i_page
latFieldId = "1DF37811-7355-4EE2-B1C7-ECBD6BE8DF44"
lngFieldId = "38732912-D8C3-46C3-9E23-6933552429FA"
apikey = ""
markers = []
}}
{{ for i_child in i_page.children
lat = i_child | sc_field latFieldId
lng = i_child | sc_field lngFieldId
if (!lat || !lng || lat == "" || lng == "")
continue
else
markers = array.add markers ("markers=icon:https://your_marker_icon_url|" + lat + "," + lng)
end
}}
{{ end }}
{{ markerstring = markers | array.join "&" }}
{{ if !o_pagemode.is_experience_editor }}
<div class="static-map">
<img loading="lazy" class="lazy" data-latlong="{{ i_contextitem | sc_field latFieldId }}|{{ i_contextitem | sc_field lngFieldId }}" data-src="https://maps.googleapis.com/maps/api/staticmap?key={{apikey}}&size=600x400&maptype=street&center={{ i_contextitem | sc_field latFieldId }},{{ i_contextitem | sc_field lngFieldId }}&{{markerstring}}" />
</div>
{{ else }}
<div class="static-map">
Static Map Hidden
</div>
{{ end }}
Content Scriban Template
A custom function called sc_searchitems was built to query the items. Your solution may only require the OOTB function sc_query or getting the children with i_page.children.
<h3 class="field-promotitle">{{ sc_field i_item 'PromoTitle' }}</h3>
{{ sc_field i_item 'PromoText' }}
{{
queryid = "{1A5CDCC5-EBB7-49B9-8C56-7E7F74BE0C26}"
fieldname = "Title"
}}
<ul class="items">
{{ for i_searchitem in ( sc_searchitems i_page queryid o: "Title,Ascending" p: 50 ) }}
<li>{{ i_searchitem.Fields[fieldname] }}</li>
{{ end }}
</ul>
Note: Example for creating the sc_searchitems function can be found here.
|
How do I render a Google static map with rendering variants?
I'm looking to generate something like the following using Google Static Maps. How would I go about setting this up with rendering variants?
| |
Welcome to Sitecore StackExchange. For sitecore 9.3 you can take a look at the approach written in the sitecore ContactManager documentation https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/contactmanager-reference.html:
var manager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;
It also contains details on modifying a contact with an ongoing session. I would suggest to try to rewrite your old code because ContactRepository is not recommended to be used, instead if you need to modify a contact you should use xConnect Client API https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/xconnect-client-api-overview.html
|
Sitecore Contacts – Create and save contacts to and from xDB (MongoDB)
When making our site in Sitecore 8.2 we have followed steps from this website
https://briancaos.wordpress.com/2015/10/09/sitecore-contacts-create-and-save-contacts-directly-to-and-from-xdb-mongodb/
but while upgrading it to Sitecore 9.3, I am not able to use many functionality like LockAttemptResult, LockAttemptStatus are deprecated.
Cannot initiate contactRepository and ContactManager with these:
ContactRepository contactRepository = Factory.CreateObject("tracking/contactRepository", true) as ContactRepository;
ContactManager contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
Anyone has better solution to perform and modify this functionality.
| |
Let's firstly define, why do you need it?
It looks like your code forces Solr to use POST requests instead of GET requests.
It is usually done to prevent error The remote server returned an error: (414) Request-URI Too Long. This error can appear if you use GET request and have quite a long search query.
If my assumption about the purpose of your code is right then here is the solution.
Sitecore 9.3 has ability to turn usage of POST requests on/off from the config file.
Open App_Config\Sitecore\ContentSearch\Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config
Find ContentSearch.Solr.SendPostRequests setting
Set value to be true
And now, you don't need to override any methods in default DefaultSolrStartUp.
P.S. It is better to patch config rather than change it directly.
|
CreateConnection method doesn't exits in DefaultSolrStartUp - Sitecore 9.3
I am in process of upgrading content serach Solr provider from Sitecore 8.2 to Sitecore 9.3.
I am facing some code issue after upgraded the dll(Sitecore.ContentSearch.SolrProvider, Version=6.0.0.0)
facing issue in creationconnection which is override from Defaultsolr setup
In the upgraded DLL Creationconnection override method does not exits.
public class DefaultSolrStartUp
{
public DefaultSolrStartUp();
[Obsolete("Please use the default constructor.")]
public DefaultSolrStartUp(IHttpWebRequestFactory requestFactory, BaseSolrSpecificSettings solrSettings);
protected IEnumerable<ISearchIndex> Indexes { get; }
[Obsolete("The property is not used and will be removed in the future.")]
protected virtual BaseSolrSpecificSettings SolrSettings { get; }
[Obsolete("The property is not used and will be removed in the future.")]
protected virtual IHttpWebRequestFactory RequestFactory { get; }
protected internal virtual DefaultSolrLocator<Dictionary<string, object>> Operations { get; internal set; }
[Obsolete("The property is not used and will be removed in the future.")]
protected internal ISolrConnector SolrConnector { get; set; }
public virtual void Initialize();
}
Code implementation
public class SolrPostStartUp : DefaultSolrStartUp
{
protected override ISolrConnection CreateConnection(string serverUrl)
{
SolrConnection basecon = new SolrConnection(serverUrl) { Timeout = SolrContentSearchManager.ConnectionTimeout };
FieldInfo field = typeof(DefaultSolrStartUp).GetField("solrCache", BindingFlags.Instance | BindingFlags.NonPublic);
var basecache = field.GetValue(this);
if (basecache != null)
{
basecon.Cache = (ISolrCache)basecache;
}
PostSolrConnection solrConnection = new PostSolrConnection(basecon, serverUrl);
return solrConnection;
}
}
Could someone please suggest the approach for the issue. Thanks in advance
| |
By default Microsoft has a character limitation for file paths. The folder and file name must remain under 260 characters. If you’re familiar with Twitter, 260 characters seems like a breeze. However, most projects easily hit that limit. For this they have created a work around in TDS.
The File Alias function in TDS allows you to shorten the file path to fit in the requirements that Microsoft set. You’ll probably see the following error if trying to sync items into a TDS project tree that already exceeds the path length:
“The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters”
Imagine you have the following tree existing in your Sitecore instance and TDS:
If you browse the tree inside Windows Explorer, you’ll see the same folder structure, replicated on the file system – this is how items are serialized:
Now let’s look at the file system alias – going back into the TDS project and viewing the properties of an item or folder in the tree, you’ll see a File system Alias section there:
Simply inserting a name of your choosing there will result in the item being renamed on the file system. In this case, we renamed the Sitecore folder named “FolderOne” to just “1”:
If we now go and check back on the file system, we’ll see that the path to our template has changed, and has effectively become shorter by 7 characters.
We can always give alias to more items in the tree, in order to achieve shorter paths:
Sometimes people get worried that the alias of items in their TDS project will screw with the item names in Sitecore. As you’ve seen above, an item consists of 2 parts – the item inside the TDS project and then the serialized .item file itself. After undergoing the alias process, the item keeps the original name and path; what changes is the path/name on the file system itself. This will not affect the name in Sitecore.
Source:
https://www.teamdevelopmentforsitecore.com/Blog/file-length-error-tds
|
How to manage TDS long files names for Continuous Integration build process?
We are trying to use Bamboo for continuous integration. During build creation we are getting errors "File Name Too Long" for tds items.
fatal: cannot create directory at 'src/Project/Website/tds/content/Sitecore.Project.Website.Content/Sitecore/Content/sample-path': Filename too long
Checkout to revision 01bd9dkdkd919276ffbd0b1024e86b3e8d14b7f42a has failed.
How we can configure continuous integration for Sitecore with TDS in this case?
| |
Assuming your markedItemIds.txt file contains comma separated IDs like {ID1},{ID2}, based on your powershell script I was able to filter the referrer ID's using:
$allImages = Get-ChildItem -Path 'master:/sitecore/media library/Images' -recurse -Language * -Version *
$results = @();
$ItemIdList = Get-Content -Path 'D:\markedItemIds.txt'
$allImages | ForEach-Object {
$linkedItemIdResults = @();
$LinkedItemIds = Get-ItemReferrer -ID $_.ID | Select-Object -Property ID
foreach ($linkedItem in $LinkedItemIds) {
foreach ($itemFileId in $ItemIdList.Split(",")) {
if ($linkedItem.ID -eq $itemFileId) {
$linkedItemIdResults += $linkedItem.ID
}
}
}
$properties = @{
Name = $_.Name
ID = $_.ID
Path = $_.ItemPath
LinkedItemIds = $linkedItemIdResults
}
$results += New-Object psobject -Property $properties
}
$results | Select-Object -Property ID, Name, Path, LinkedItemIds
|
How can I get List of Images that directly linked with specific Page Items?
Have a scenario, where wanted to get list of Images which directly linked with marked page items.
Below is the powerShell script which I am trying, please help
$allImages = Get-ChildItem -Path 'master:/sitecore/media library/Images' -recurse -Language * -Version *
$results = @();
[string[]]$ItemIdList = Get-Content -Path 'D:\markedItemIds.txt'
$allImages | ForEach-Object {
$properties = @{
Name = $_.Name
ID = $_.ID
Path = $_.ItemPath
LinkedItemIds = Get-ItemReferrer -ID $_.ID | Select-Object -Property ID
//wanted to apply condition -> LinkedItemIds matched with ItemIdList if true then get value
}
$results += New-Object psobject -Property $properties
}
$results | Select-Object -Property ID, Name, Path, LinkedItemIds
| |
You can download 4.0.5 version from here: https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.5-signed.msi
I can see also 4.0.6-4.0.10 are compatible with Sitecore 9.3
|
Mongo 4.0.5 version isn't available in Mongo Site
Sitecore 9.3 recommends to use mongo 4.0.5 version. But I cannot find the exact version on the mongo website (https://www.mongodb.com/try/download/community)
Appreciate any help on this .
| |
There is no one good way of setting up roles for environments. It all depends on your project specific requirements and load.
Sample configuration which is an example of Sitecore 10 setup goes like that:
Identity Server
CM + xDB Reporting
CD
xDB Processing
Cortex Reporting Service + Marketing Operations + Marketing Automation reporting + xConnect Collection search
Cortex Processing service + xxConnect Collection + xConnect Reference data
(Horizon?)
While it may work well in some cases, in other it may be better to have e.g. separate server for reporting role.
Here is an article describing ARM templates for Sitecore 10 XP, topologies and tiers. While it may not be up to date, it kind of shows it quite well where the load goes and how your resources need to grow depending on the number of visits:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0923605
|
Sitecore 9.3.0 XP Scaled instance on Developer Machine
I installed scaled architecture in my developer machine. I see 12 processes in IIS
XP1.sitecore.CM,
XP1.sitecore.identityserver
XP1.sitecore.CD
XP1.sitecore.collection
XP1.sitecore.ma
XP1.sitecore.reporting
XP1.sitecore.processingEngine
XP1.sitecore.refdata
XP1.sitecore.reporting
XP1.sitecore.search
XP1.sitecore.rep
XP1.sitecore.prc
Each process has own configurations and connection string. I would like to know how to setup in Higher environment. Do we really need to use dedicated server for each role in higher environment( DEV, QE) ?
Could anyone please suggest the recommended approach and how to segregate the above roles in higher environment. Thanks in advance!!
| |
I managed to get it working using this approach:
$item = Get-Item -Path "master:{F4819743-C9D5-48A4-911B-017F8BA1415C}"
# Change the name 'ShowRule' to whatever your rule field is called
$renderer = New-Object Sitecore.Shell.Applications.Rules.RulesRenderer ($item.ShowRule)
$sw = New-Object System.IO.StringWriter
$renderer.Render($sw)
$records = @()
$records += [PSCustomObject]@{
"RuleHtml" = $sw.ToString()
}
$records | Show-ListView
|
Retrieve Rules field using Powershell script in readable format
We are trying to get report using Powershell to list all sub items under one item and some of it's fields. One field in the item is of Rules field type. We are able to fetch RuleSet XML (<rulesetCustom Rules>) from the field. However we need it in readable format as shown in Content Editor.
Is there any way to fetch it using Powershell?
Thanks,
PC
| |
You need to configure four settings:
Enable site-level language fallback
Specify the language fallback rules
Enable item level fallback
Enable field level fallback
Sounds like you have configured the first two settings (please ensure you are looking at the correct version of Sitecore too)
Please ensure you review this full list here
|
Language fallback working on CM but not on CD
I've enable Language Fallback and everything works as expected on CM, but things are not working out on CD.
I've checked the config to be the same on both CM and CD (/App_Config/Sitecore/CMS.Core/Sitecore.LanguageFallback.config)
Languages in Sitecore have the fallback language setup and (re)published.
Other settings I didn't do. Am I missing something?
| |
Set "IsCxaSite" to true in "Site Grouping" item for that SXA site and then try to trigger cxa api's.
|
Ajax Begin Form Api Route is different in 10.1
I'm using XP 10.1 & XC 10.1
The following way used to work in earlier versions of XP.
using (Ajax.BeginForm("SaveContactUsFormData", "ContactUsForm",
new AjaxOptions
{
HttpMethod = "Post",
OnSuccess = "OnSuccessContactUs",
OnFailure = "OnFailureContactUs",
LoadingElementId = "divLoading"
}))
{
@Html.AntiForgeryToken()
<button type="submit">Submit</button>
}
But now it renders the form action url as - /api/cxa/ContactUsForm/SaveContactUsFormData
I'm expecting the url should be - /api/sitecore/ContactUsForm/SaveContactUsFormData. Is that correct or has it changed for commerce (or xp 10.1).
The controller method is not triggered on debug and the button click is doing a postback instead of an asynchronous call.
UPDATE:
The code in the action method does execute without any errors.
| |
Media Request Protection only kicks in when it needs to. It is designed to prevent media specific parameters from being manipulated (e.g. specifying a MaxWidth for an image of 10248000, forcing Sitecore to fill its media cache with useless scaling of images).
Therefore if no parameter is present on your media url, no hashing is required. Sitecore will server the image as-is.
Adding for instance a MaxWidth limitation to your image url rendering (which would be a recommended practice in any event), Media Request Protection kicks in and generates a hash for your image.
Example: string imageUrl = HashingUtils.ProtectAssetUrl(MediaManager.GetMediaUrl(imageField.MediaItem, new MediaUrlOptions {MaxWidth = 1024}))
|
Media handle hash not being generated
I am using Sitecore 9.1.1 with SXA 1.8.1.
I am trying to generate the image URL with hash programmatically. I tried the following code but the HashingUtils does not seem to be working - the image URL is correct but the hash is not generated.
Media.RequestProtection.SharedSecret was set and the Request Protection is enabled.
Using FieldRenderer for images generates the hash in other places on the website so I assume something is wrong with my code. Can you spot something?
ImageField imageField = item.Fields[fieldId];
if (imageField != null && imageField.MediaItem != null)
{
var mediaSrc = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(imageField.MediaItem, new MediaUrlOptions { Language = Context.Language })) ?? string.Empty;
var imageUrlWithHash = HashingUtils.ProtectAssetUrl(mediaSrc);
return string.IsNullOrEmpty(mediaSrc) ? string.Empty : $"<img src=\"{imageUrlWithHash}\" />";
}
As the output of this code I'm getting the URL without the hash:
<img src="/-/media/Project/myimagename.jpg">
Any ideas what could be causing that?
| |
indexAllFields is a property of SolrDocumentBuilderOptions, not SolrIndexConfiguration.
Try using patch like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultSolrIndexConfiguration>
<documentOptions type="Sitecore.ContentSearch.SolrProvider.SolrDocumentBuilderOptions, Sitecore.ContentSearch.SolrProvider">
<indexAllFields>true</indexAllFields>
</documentOptions>
</defaultSolrIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
|
Could not find property 'IndexAllFields' on object of type: Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration
I have tried adding IndexAllFields as true in C:\inetpub\wwwroot\subway93sc.dev.local\App_Config\Sitecore\ContentSearch\Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config.
But it does not work.
Could you please provide me with any suggestion to resolve this error?
| |
It looks like Token-based authorization for RESTful ItemService was enabled in the Sitecore version you are upgrading, but for Sitecore 9.3, there have been few changes in assembly and namespaces. Please check for the configuration in your solution for it (search for signingProvider) and update the type for signingProvider - Sitecore.Services.Infrastructure.Security.SymmetricKeySigningProvider, Sitecore.Services.Infrastructure
This final patch will look like this -
<configuration>
<sitecore>
<api>
<tokenSecurity>
<signingProvider type="Sitecore.Services.Infrastructure.Security.SymmetricKeySigningProvider, Sitecore.Services.Infrastructure">
<param desc="connectionStringName">Sitecore.Services.Token.SecurityKey</param>
</signingProvider>
</tokenSecurity>
</api>
</sitecore>
</configuration>
|
Could not resolve type name: Sitecore.Services.Infrastructure.Sitecore.Security.SymetricKeySigningProvider, Sitecore.Services.Infrastructure.Sitecore
I am working on Sitecore 9.3 Upgradation, and After upgrading the dll's and published to Sitecore 9.3 Instance, facing the below error. Kindly suggest
Could not resolve type name: Sitecore.Services.Infrastructure.Sitecore.Security.SymetricKeySigningProvider, Sitecore.Services.Infrastructure.Sitecore (method: Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert)).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: Could not resolve type name: Sitecore.Services.Infrastructure.Sitecore.Security.SymetricKeySigningProvider, Sitecore.Services.Infrastructure.Sitecore (method: Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert)).
| |
This error is due to an issue with Service Monitor which affects Sitecore containers based on Windows Server Core LTSC2019. The original entrypoint for the Sitecore CM container in 10.0 used ServiceMonitor.exe to start and monitor the w3wp service.
As this issue only affects LTSC2019, one fix is to switch to one of the SAC images available from Sitecore by changing the SITECORE_VERSION environment variable that's used in the default Compose configuration.
SITECORE_VERSION=10.0.0-1909
Sitecore has also resolved this issue in the latest patch releases for Sitecore 10.0.1 by replacing ServiceMonitor.exe with a custom script, one that was already being used in Sitecore 10.1. To get this update, ensure your SITECORE_VERSION is either 10.0-ltsc2019 or 10.0.1-ltsc2019 and pull the latest images:
docker-compose -f .\docker-compose.yml pull
If you are using Sitecore Docker Tools and its development entrypoint, you need to ensure you have the latest patch release of it as well.
docker pull scr.sitecore.com/tools/sitecore-docker-tools-assets:10.0.0-1809
If you are building custom images for your Sitecore containers, after pulling the latest base images and Sitecore Docker Tools images, you'll also need to rebuild your containers.
docker-compose build
|
Sitecore containers exit with "Failed to update IIS configuration" error
I am attempting to run Sitecore 10.0 in containers, but the environment fails to start successfully. If I try to access my Content Management container, I get a 404 error:
404 page not found
I see that my cm and xconnect containers have exited. Running docker-compose logs cm or docker-compose logs xconnect reveals the following error:
Service 'w3svc' has been stopped
APPCMD failed with error code 259
Failed to update IIS configuration
How can I get my container environment to start successfully?
| |
Both official and community Sitecore images tags are listed in the sitecore-tags.md file on the docker-images Sitecore repository:
https://raw.githubusercontent.com/Sitecore/docker-images/master/tags/sitecore-tags.md
This file has grown so much that only its raw version is now readable on the GitHub portal. Quoting here its first section for more readability:
This document provides a list of the images and tags available on the official Sitecore container registry hosted at scr.sitecore.com.
The Sitecore container images are structured in namespaces according to product line:
sxp: Contains all Sitecore Experience Platform (SXP) image repositories. Primary platform repositories are found at the root.
sxp/nonproduction: Images for SXP supporting roles intended for development and testing. No production support is provided for images labeled as nonproduction.
sxc: Contains all Sitecore Experience Commerce (SXC) image repositories. Primary SXC repositories are found at the root.
sxc/nonproduction: Images for SXC supporting roles intended for development and testing. No production support is provided for images labeled as nonproduction.
sxp/modules: Contains image repositories for SXP-specific modules.
tools: Tools to support Sitecore products.
demo: Images in this namespace are built from the https://github.com/sitecore/Sitecore.Demo.Platform GitHub repository and are meant to support non-production training, experimentation, and demonstration scenarios. Support for these images is community-driven and not provided by Sitecore Support. Please see the GitHub repository for more details.
demo/base: Images in this namespace are built from the https://github.com/sitecore/Sitecore.Demo.Base GitHub repository and are base images for the /demo/lighthouse images. They are meant to support non-production training, experimentation, and demonstration scenarios. Support for these images is community-driven and not provided by Sitecore Support. Please see the GitHub repository for more details.
community: Images in this namespace are built from the https://github.com/sitecore/docker-images GitHub repository and are meant to support non-production training, experimentation, and demonstration scenarios. Support for these images is community-driven and not provided by Sitecore Support. Please see the GitHub repository for more details.
community/modules: Images in this namespace are module asset images built from the https://github.com/sitecore/docker-images GitHub repository and are meant to support non-production training, experimentation, and demonstration scenarios. Support for these images is community-driven and not provided by Sitecore Support. Please see the GitHub repository for more details.
sch: Contains all Sitecore Content Hub (SCH) image repositories.
|
Sitecore Docker Registry Versions
I need to add the Management module to my image. The instructions are on the Sitecore, but the compose files all append a specific version to the images to pull.
How do I find the available versions on the Sitecore Docker registry for any module?
| |
You have three options how to handle upgrade:
Lift and shift what you already have in terms of content, DevOps pipelines, and infrastructure and just take what you have in Sitecore 10.0, prepare new environments / app services with Sitecore 10.1, update NuGet references and deploy it there.
In place upgrade - Follow the official documentation located here - chapter 4.2.6 Upgrading from Sitecore XP 10.0.1 or earlier
Leverage latest Docker support introduced with Sitecore 10.1 and completely rebuild your deployment and infra strategy leaving App Services behind and reconfiguring everything using Docker or better Kubernetes Services in Azure. In this case, follow "Upgrade Container Deployment Guide" located here
|
Upgrade Sitecore 10.0 to 10.1 in Azure App Service
I'm looking for a guide step by step to upgrade existing Sitecore 10 to 10.1 without making massive changes to environment.
Do we need to spin new App Service webapp to start fresh installation process of SC10.1?
Is there a quick way to upgrade existing App service test environment without setting up new app service web app?
Note: We have migrated SC8.2 to SC10 in new Azure App service (Test/UAT) env. Still time to for us to go into production. With SC10.1 release we are in a view to upgrade existing test/uat to 10.1
Any help, guidance is most welcome.
Thanks for your help.
| |
You would need to rewrite your code to not inherit from Element as it is removed in later versions. You can also take a look at the implementation in 10.1 for the models in the namespace Sitecore.Analytics.Model.Generated.
The methods EnsureAttribute, EnsureDictionary, EnsureElement were used in the constructor as a check to add the object to the collection if it didn't exist, but in the newer versions these aren't used anymore.
public ContactPhoneNumbers()
{
this.EnsureAttribute<string>(nameof (Preferred));
this.EnsureDictionary<IPhoneNumber>(nameof (Entries));
}
public ContactPhoneNumbers()
{
}
Instead of SetAttribute and GetAttribute you would need to read the values from the Fields collection, for example:
public string Country
{
get => this.GetAttribute<string>(nameof (Country));
set => this.SetAttribute<string>(nameof (Country), value);
}
Address.Fields uint16 = (Address.Fields) info.GetUInt16("f");
if (uint16.HasFlag((Enum) Address.Fields.Country))
this.Country = info.GetString("c");
public string Country { get; set; }
The same would be for GetCollection:
public IElementCollection<ITagValue> Values => this.GetCollection<ITagValue>(nameof (Values));
[Obsolete("Deprecated in 10.0.0. Use Entries instead.")]
public IElementCollection<ITagValue> Values => (IElementCollection<ITagValue>) new ElementCollection<ITagValue>(this.Entries);
public IList<ITagValue> Entries => this._entries ?? (this._entries = (IList<ITagValue>) new List<ITagValue>());
|
Sitecore.Analytics.Model.Framework.Element is obsolete - What is the replacement
In Sitecore 9.3 Sitecore analytics, if I try and inherit Element, I see an obsolete message:
Assembly Sitecore.Analytics.Model, Version=14.0.0.0
[Obsolete("Will be removed in the next version.")]
public abstract class Element : IElement, IValidatable
{
protected Element();
public bool IsEmpty { get; }
protected IModelMemberCollection Members { get; }
protected void EnsureAttribute<TValue>(string name);
protected void EnsureCollection<TElement>(string name) where TElement : class, IElement;
protected void EnsureDictionary<TElement>(string name) where TElement : class, IElement;
protected void EnsureElement<TElement>(string name) where TElement : class, IElement;
protected TValue GetAttribute<TValue>(string name);
protected IElementCollection<TElement> GetCollection<TElement>(string name) where TElement : class, IElement;
protected IElementDictionary<TElement> GetDictionary<TElement>(string name) where TElement : class, IElement;
protected TElement GetElement<TElement>(string name) where TElement : class, IElement;
protected virtual void OnValidate();
protected void SetAttribute<TValue>(string name, TValue value);
}
What is the replacement of GetElement<TElement>, SetAttribute<TValue> and GetCollection<TElement> in Sitecore 9.3 xConnect.
Is there an example somewhere. Thanks in Advance!!
| |
This is how query strings works. Browser needs to know which part of url is protocol (knows it as url contains // and http or http or ftp before), which part is domain (knows it because of . like .com, .net, ...) and ? is used for query strings so everything which is after this character is considered as query string to pass some parameters towards server.
Query String Definition
A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML form.
A web server can handle a Hypertext Transfer Protocol (HTTP) request either by reading a file from its file system based on the URL path or by handling the request using logic that is specific to the type of resource. In cases where special logic is invoked, the query string will be available to that logic for use in its processing, along with the path component of the URL.
Structure
Typical URL containing a query string is as follows:
https://example.com/over/there?name=ferret
When a server receives a request for such a page, it may run a program, passing the query string, which in this case is, name=ferret unchanged, to the program. The question mark is used as a separator, and is not part of the query string.
Web frameworks may provide methods for parsing multiple parameters in the query string, separated by some delimiter. In the example URL below, multiple query parameters are separated by the ampersand, "&": https://example.com/path/to/page?name=ferret&color=purple
Source: https://en.wikipedia.org/wiki/Query_string
|
How link is created in CTA link in Sitecore sxa?
We would like to understand how Sitecore SXA create a link for CTA link component ?
We use CTA link in Sitecore and add link through Internal Link and provide Query string value here. When we check this link in Experience Profile then it is showing query string with ? mark.
Example : https://domain.com?name=value
Need to understand , where are they adding ? in URL in CTA link in Sitecore code.
| |
The easiest way to clean the HTML cache is to trigger publish.
Sitecore doesn't have watchers on .cshtml files, so it is expected behavior.
|
How to ensure rendering cache invalidates after a direct edit to the .CSHTML file
I have a case where I needed to apply a hotfix to a component CSHTML view file. I edited the file on both of our Content Delivery servers. I also cleared the entire Sitecore cache via /sitecore/admin/cache.aspx. At that point I was expecting to see the updated HTML on the front end, but it was still in its previous state.
It wasn't until I recycled the IIS app pools that the HTML was updated. If I recall correctly, on all of my other Sitecore projects, whenever a view file was edited and saved, the front end would update almost instantaneously. Why isn't this happening in this case?
Here are the cache settings on the component:
Setup:
Sitecore 9.0.2
Content Management server
Two Content Delivery servers
| |
For the above issue, I raised the ticket in Sitecore support portal. Here is the response of the above issue from sitecore support portal. It works fine for me.
Please ensure that you had created "Sitecore Id" field in your Salesforce as it describes in chapter 1.5. "Add a custom field in Salesforce (optional)" of the installation guide?
https://sitecoredev.azureedge.net/~/media/630DFC39E8F34EB1965624783D1701F9.ashx?date=20200825T102007
Also please ensure that the salesforce user which is used for Sitecore connection has permissions to create and edit contacts and all contacts fields.
As far as I see, such an error can also occur when the user hasn't rights to edit the field.
Please check that salesforce user has appropriate rights to edit Sitecore Id field - https://developer.salesforce.com/docs/atlas.en-us.securityImplGuide.meta/securityImplGuide/users_profiles_field_perms.htm
|
Error occured while synchronizing xconnect contacts to salesforce
I am using Sitecore XP 9.3 to synchronize contacts data from Sitecore to salesforce and vice versa.
For this, I installed the Sitecore Data Exchange framework 4.0 package and Sitecore connect for Salesforce CRM 4.0 . After did a set up , I ran the pipeline batch xconnect contacts to salesforce sync , it throws the error
ERROR [Data Exchange] Record was not
saved:INVALID_FIELD_FOR_INSERT_UPDATE* and
*ERROR [Data Exchange] Record was not saved:Event: bad field names on insert/update call: SitecoreId__c
Can anyone help to me fix this error?
While I ran the Pipeline batch Salesforce contacts to Xconnect sync, It's working fine.
I referred the below blog for do this.
https://varunvns.wordpress.com/2019/05/31/sitecore-salesforce-setting-up-salesforce-connect/
https://varunvns.wordpress.com/2019/06/22/sitecore-salesforce-connecting-sitecore-contacts-with-salesforce-contacts/
Thanks in Advance
| |
You can find it here - https://doc.sitecore.com/developers/91/sitecore-experience-platform/en/rebuilding-the-xdb-search-index.html
Some important steps after creating xDB core -
To invoke the rebuild request command:
Go to the server where the xConnect Search Indexer is running and open a command line.
Go to the xConnect Collection Search IndexWorker folder: <xConnect Collection Search service root>\App_Data\jobs\continuous\IndexWorker.
Run XConnectSearchIndexer -rr (alternatively XConnectSearchIndexer -requestrebuild). The command registers a small document in the live core signaling that the rebuild should be started. The xConnect Search Indexer will notice the document and start the rebuild process.
Note - Check in Sitecore 9.3 it is Sitecore.XConnectSearchIndexer instead of XConnectSearchIndexer
|
How to build xdb index in Sitecore 9.1.1?
We need to rebuild xdb index in Sitecore 9.1.1. I am new in Sitecore. Kindly someone assist me how can I rebuild xdb index in Sitecore 9.1.1.
| |
Facets work on fields. So you should have a field in your items that determines if the item is a product or an article (or ...). This could be the template, but that is rarely named as you want it.
I solved a similar issue with a computed field. I added a computed field into my (sxa) index that contains the text you want as facet based upon the logic you need. So, in your example you should store "Products" for each product item, "Articles" for each article item and so on...
Once this is done (don't forget to rebuild the index to populate the newly created computed field), you can create the facet on this computed field.
Update
Based upon your comment, the question became a bit more clear. If you want the content authors to select which results a search should contain, you don't need a facet but a scope. You can read more on those here: https://doc.sitecore.com/users/sxa/93/sitecore-experience-accelerator/en/sxa-search-facets,-scopes,-and-tokens.html
You could use the same computed field for the scope(s) - but for scopes you probably won't need it. You are able to define the scopes easily based upon the location and/or the template. Your editor should pick the scope in the search result component.
|
Sitecore sxa custom filter based on content tree multiple node selection as datasource
We have a specific requirement in sxa search, we want to create a facet based on datasource selected from one of the treelist field which hold some node from content tree, for example Article and Product node. So we need Article and Product in facet and based on selection we want to show the children item in search. Let say if user select Article node then in search result show all children node of Article.
Let say All items under specific node which selected in treelist but how can we make it as facet.
Assume we have below content tree structure :
Home
Products
Product 1
Product 2
Articles
Article 1
Article 2
Events
Event1
Event2
If we select below node from treelist for facet source :
Products
Articles
Facet must be look like
Section (facet title)
Products
Articles
Assume if user select "Products" then search result must be:
Product 1
Product 2
Suggestions will be appreciated :)
| |
Out-of-the-box, Sitecore does not provide a solution for Wildcard pages and the related tools (Analytics Tracking, Path Analyzer, and so on).
You need to implement a custom solution for correctly instructing Sitecore what your Wildcard matches.
I am not sure if this code can run on Sitecore 9.1 (it is for 8.x), but it should give you a place to start.
using Sitecore;
using Sitecore.Analytics.Tracking;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Web;
using System;
using System.Web;
using Sitecore.Analytics.Pipelines.InitializeTracker;
namespace Someproject.Pipelines.InitializeTracker
{
public class CustomCreatePage : InitializeTrackerProcessor
{
private void CreateAndInitializePage(HttpContextBase httpContext, CurrentInteraction visit)
{
IPageContext empty = visit.CreatePage();
empty.SetUrl(WebUtil.GetRawUrl());
DeviceItem device = Context.Device;
if (device == null)
{
empty.SitecoreDevice.Id = Guid.Empty;
empty.SitecoreDevice.Name = string.Empty;
}
else
{
empty.SitecoreDevice.Id = device.ID.Guid;
empty.SitecoreDevice.Name = device.Name;
}
// Default Sitecore implementation
Item item = Context.Item;
// Our logic starts here: if the current item is a wildcard
if (item != null && item.Name == "*")
{
// Perform a call to the logic which resolves the correct item
var resolvedItem = this.ResolveWildcardItem(item);
if (resolvedItem != null)
{
item = resolvedItem;
}
}
// Resume the default behaviour
if (item == null)
{
return;
}
empty.SetItemProperties(item.ID.Guid, item.Language.Name, item.Version.Number);
}
public override void Process(InitializeTrackerArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (args.IsSessionEnd)
{
return;
}
HttpContextBase httpContext = args.HttpContext;
if (httpContext == null)
{
args.AbortPipeline();
return;
}
this.CreateAndInitializePage(httpContext, args.Session.Interaction);
}
private Item ResolveWildcardItem(Item item)
{
return Someproject.BusinessLogic.AbstactedData.GetDataSource(item, Someproject.BusinessLogic.SlugFactory.GetSlugPreSelected(item));
}
}
}
The code would need to be patched in:
<?xml version="1.0" ?>
<configuration xmlns :patch="http://www.sitecore.net/xmlconfig /" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<pipelines>
<initializeTracker>
<processor type="Someproject.Pipelines.InitializeTracker.CustomCreatePage,Someproject" patch:instead="*[@type='Sitecore.Analytics.Pipelines.InitializeTracker.CreatePage, Sitecore.Analytics']" />
</initializeTracker>
</pipelines>
</sitecore>
</configuration>
Sources:
https://lostinsitecore.com/2018/02/03/sitecore-wildcard-design-pattern-and-profile-cards/
https://www.suneco.nl/blogs/track-the-correct-wildcard-item
|
Path-analyzer report for wildcard items
Sitecore: 9.1 + JSS 11 - Integrated mode
Module: Path analyzer
Issue:
We are using wild-card functionality to render certain pages in our application.
In the path-analyzer report, we are seeing '*' (aestrik) under 'Name', not the name of the item to which the request had been resolved.
Are we missing something?
| |
Sitecore XConnect provides some default collection models to save user data like Personal Information, Email, Address, etc. the complete list you can find in an assembly named Sitecore.XConnect.Collection.Model.dll.
You need to perform the below-mentioned steps to create custom facets in Sitecore.
Create a Custom Facet Model
Register the Custom Facet Model
Deploy custom Facet model to XDB
Add Custom Facet Model to Configuration
You can find step by step details about the above points from here: create-custom-facet-model-in-sitecore-9
Now next point is once you created the Custom facets then How will you use those? For the same you can follow the below blog:
work-with-custom-facet-in-Sitecore
Let me know in case you find any trouble, I am glad to help you.
|
How to replace custom facet to an Sitecore 9.3
I am implementing custom xDB facets from Sitecore 8.2 to Sitecore 9.3. I have a facet called "Data" and ICentralData Inherited from IElemenet. Now IElement is an obsolute in Sitecore 9.3. It is unclear to me how to implement the facet and element in Sitecore 9.3.
public interface ICentralData : IElement
{
IPreferences Preferences { get; }
IElementCollection<IFavoriteTool> FavoriteTools { get; }
}
// Unclear to replace the below methods in Sitecore 9.3
GetElement, GetCollection, EnsureElement, EnsureCollection
public class CentralData : Element, ICentralData
{
private const string PREFERENCES = "Preferences";
private const string BOOKMARKS = "Bookmarks";
public IPreferences Preferences
{
get { return GetElement<IPreferences>(PREFERENCES); }
}
public IElementCollection<IBookmark> Bookmarks
{
get { return GetCollection<IBookmark>(BOOKMARKS); }
}
public CentralData()
{
this.EnsureElement<IPreferences>(PREFERENCES);
this.EnsureCollection<IBookmark>(BOOKMARKS);
}
}
// would like to understand the replacement of the below methods inside custom facet
GetAttribute, SetAttribute, EnsureAttribute
[Serializable]
public class Data: Facet
{
private const string PERSONID = "PersonId";
private const string centralData = "centralData";
public int PersonId
{
get
{
return GetAttribute<int>(PERSONID);
}
set
{
SetAttribute(PERSONID, value);
}
}
public ICentralData CentralData
{
get { return GetElement<ICentralData>(centralData); }
}
public Data()
{
this.EnsureAttribute<int>(PERSONID);
this.EnsureElement<ICentralData>(centralData);
}
}
As per my understating, I need to create an XConnect custom facet but I'm a bit unclear about Elements and attributes.
Appreciated it anyone can help with this. Thanks in advance!!
| |
This is not an SXA or Scriban problem, this is a CSS problem. You can use the :nth-child() psuedo-selector to apply a style.
For example, if you want all even-numbered divs to have your .reversed css applied, then instead of having:
.landing-feature-card.reverse {
/* some styles here */
}
you could use:
.landing-feature-card:nth-child(even) {
/* some styles here */
}
If you wanted odd-numbered rows, use nth-child(odd), you can even put a formula in there, for example, if you wanted every 3rd row styled, use nth-child(3n+0), if you want every 3rd row but starting with the first row, nth-child(3n+1). You have a lot of options with just CSS.
Now your Scriban just becomes a simple loop:
{{ for i_child in (sc_followmany i_item "Landing Feature Content") }}
<div class="landing-feature-card">
<div class="inner-wrapper">
<div class="landing-feature__image">
{{ i_child.Image}}
</div>
<div class="landing-feature__text">
<p class="landing-feature__label"> {{ i_child.Featured}}</p>
<h3 class="landing-feature__title">{{ i_child.Title}}</h3>
<div class="landing-feature__description">
{{ i_child.Description}}
</div>
<div class="landing-feature__cta">
<a class="link" href="{{ sc_link i_child }}">{{ i_child.CTA }}</a>
</div>
</div>
</div>
</div>
{{ end }}
no need for complex logic, just let CSS handle it all.
|
Apply a CSS class to every alternative div using Sitecore SXA
I need to create an SXA component in which I need to apply a specific CSS class to each alternative div.
The component should read the item from a multi-list and then render the HTML and apply a reverse CSS class to each alternative div.
<div class="landing-feature-card reverse">
I have currently used SXA Scriban to do it but there is a lot of duplicate code. Is there a more efficient way to implement this
{{x=1}}
{{ for i_child in (sc_followmany i_item "Landing Feature Content") }}
{{- if x%2 == 0 -}}
<div class="landing-feature-card reverse">
<div class="inner-wrapper">
<div class="landing-feature__image">
{{ i_child.Image}}
</div>
<div class="landing-feature__text">
<p class="landing-feature__label"> {{ i_child.Featured}}</p>
<h3 class="landing-feature__title">{{ i_child.Title}}</h3>
<div class="landing-feature__description">
{{ i_child.Description}}
</div>
<div class="landing-feature__cta">
<a class="link" href="{{ sc_link i_child }}">{{ i_child.CTA }}</a>
</div>
</div>
</div>
</div>
{{ else -}}
<div class="landing-feature-card">
<div class="inner-wrapper">
<div class="landing-feature__image">
{{ i_child.Image}}
</div>
<div class="landing-feature__text">
<p class="landing-feature__label"> {{ i_child.Featured}}</p>
<h3 class="landing-feature__title">{{ i_child.Title}}</h3>
<div class="landing-feature__description">
{{ i_child.Description}}
</div>
<div class="landing-feature__cta">
<a class="link" href="{{ sc_link i_child }}">{{ i_child.CTA }}</a>
</div>
</div>
</div>
</div>
{{ end -}}
{{x=x+1}}
{{ end }}
| |
As Marek suggested above, We reached out to Sitecore support for this issue and they confirmed that this is a bug in Sitecore 9.3. This bug has reference number 420812 and it was fixed in Sitecore 10.
You can find the Hotfix package for this bug in this KB article:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0997904
This hotix provide fixes for for page EventQueueStats.aspx that might fail with error getTimestampForLastProcessingMI is null, also for administration pages like Logs.aspx and SqlShell.aspx.
|
Error while accessing EventQueueStats.aspx
Sitecore 9.3 with SXA
I am getting the below exception while accessing the Event Queue Statistics page in Sitecore.
URL: <cm_domain>/sitecore/admin/EventQueueStats.aspx
22180 05:16:57 ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.sitecore_admin_eventqueuestats_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.InvalidOperationException
Message: getTimestampForLastProcessingMI is null
Source: Sitecore.Kernel
at Sitecore.Diagnostics.Assert.IsNotNull(Object value, String message)
at Sitecore.ExperienceContentManagement.Administration.EventQueueStats.ReloadStatistics()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Checked I'm able to access and query the [EventQueue] table in <InstanceName>_Master DB.
Any help will be much appreciated?
| |
I was able to copy child items from one folder to another using this simple script:
$targetPath = "/sitecore/content/home/test2/"
$itemAChildren = Get-ChildItem -Path "/sitecore/content/home/test1" -recurse
$itemBChildren = Get-ChildItem -Path "/sitecore/content/home/test2" -recurse
foreach ($itemAChild in $itemAChildren) {
$exists = 0
$createpath = $targetPath
foreach ($itemBChild in $itemBChildren) {
if ($itemAChild.Name -eq $itemBChild.Name) {
$exists = 1
}
}
if ($itemAChild.Parent.Paths.Path -eq "/sitecore/content/Home/Test1") {
$createpath = $targetPath
}
else
{
$createpath = $itemAChild.Paths.Path
$createpath = $createpath -replace "/sitecore/content/Home/Test1", "/sitecore/content/home/test2"
}
if($exists -eq 0) {
Copy-Item -Path $itemAChild.ItemPath -Destination $createpath
}
}
|
Compare two items and copy missing children using Powershell
Environment: Sitecore 9.2 & SXA 1.9
Scenario: I have two different items and I would like to compare them and copy the missing children from one item to another using Powershell script.
Item A (DifferenceObject) - If empty copy all the children from Item
B and if few children are missing then copy them from Item B without
disturbing the other children of Item A.
Item B (ReferenceObject) - This item can have grandchildren as well.
This is the script that I am using but while running this script on the same item twice, it is making duplicate copies of children instead of ignoring them.
$itemA = Get-ChildItem -Path "/sitecore/home/itemA"
$itemB = Get-ChildItem -Path "/sitecore/home/itemB"
$diffs = Compare-Object -ReferenceObject $itemB -DifferenceObject $itemA |
Where-Object { $_.SideIndicator -eq "<=" } | Select-Object -ExpandProperty InputObject
$diffs | Copy-Item -Destination $itemA.ID -Recurse
How to achieve this functionality? Thanks.
| |
I was able to accomplish this in a few steps in SXA 9.3. This approach implements the ISearchService included with SXA. We're basically extracting code that is used by the SearchController.
Step 1 : Implement the custom search function. Add this to your IGenerateScribanContextProcessor.
private delegate IEnumerable<Item> SearchItemsDelegate(Item item, string s, string q = null, string o = null, int p = 10, int e = -1, string g = null, double r = -1);
protected ISearchService SearchService { get; } = ServiceLocator.ServiceProvider.GetService<ISearchService>();
protected ISortingService SortingService { get; } = ServiceLocator.ServiceProvider.GetService<ISortingService>();
public IEnumerable<Item> SearchItemsImpl(Item item, string s, string q = null, string o = null, int p = 10, int e = -1, string g = null, double r = -1)
{
var siteInfo = SiteResolver.GetSiteInfo(item);
var scopesIDs = s?.Split(',', '|').Where(ID.IsID).Select(ID.Parse);
Coordinate center = null;
if (!string.IsNullOrEmpty(g))
{
center = g?.Replace("|", ",");
}
var query = this.SearchService.GetQuery(new SearchQueryModel
{
Coordinates = center,
ItemID = item?.ID,
Query = q,
ScopesIDs = scopesIDs
}, out var indexName);
var sortings = o?.Split('|').TrimAndRemoveEmpty();
query = this.SortingService.Order(query, sortings, center, siteInfo.Name);
if (e > 0)
{
query = query.Skip(e);
}
if (p > 0)
{
query = query.Take(p);
}
return query.Select(i => i.Uri).ToList()
.Select(u => Factory.GetDatabase(u.DatabaseName)
.GetItem(u.ItemID, u.Language, u.Version));
}
Step 2 : Add the function to the global script object.
args.GlobalScriptObject.Import("sc_searchitems", new SearchItemsDelegate(SearchItemsImpl));
Step 3 : Add a scriban rendering variant.
{{
queryid = "{BBC62A76-2207-465B-BA0D-073BE71FD90C}"
fieldname = "Title"
}}
<ul class="items">
{{ for i_searchitem in ( sc_searchitems i_page queryid o: "Title,Ascending" p: 50 ) }}
<li>{{ i_searchitem.Fields[fieldname] }}</li>
{{ end }}
</ul>
Note: This version may have some missing features. If you improve upon feel free to share with me and I'll update this answer.
Update: You may have noticed that at the end of the code where the items are pulled from the search engine that Uri is selected. In my experience I've found that the SXA search can be made significantly faster by selected just the Uri from the search engine and then getting items based on that property. A feature request would be for SXA to do the same by default.
|
How do you create a scriban function which implements the Content Search API?
I've seen examples such as here on how to create a custom Scriban function.
How would I go about implementing one which supports the Content Search API like that shown here?
Example: Function called sc_searchitems calls the Content Search API.
<h3 class="field-promotitle">{{ sc_field i_item 'PromoTitle' }}</h3>
{{ sc_field i_item 'PromoText' }}
{{
queryid = "{1A5CDCC5-EBB7-49B9-8C56-7E7F74BE0C26}"
fieldname = "Title"
}}
<ul class="items">
{{ for i_searchitem in ( sc_searchitems i_page queryid o: "Title,Ascending" p: 50 ) }}
<li>{{ i_searchitem.Fields[fieldname] }}</li>
{{ end }}
</ul>
| |
Email Experience Manager(ExM) doesn't send and finish all things related to email immediately.
Your code will put the email into an "automated message bus". And then your email will be sent. After sending of email, other tasks will be executed, e.g. update reporting database with data about the new email. It happens quickly, but not immediately. That is why you could not execute removing a contact right after calling Send method. Because contact is still required to properly finish all tasks.
You have a few options how to overcome it:
Try to use the "Exclude From Reports" and "Service Message" checkboxes on your email. (Hopefully, it will work, if not you will need to chose between 2nd and 3rd)
Use marketing automation tool. Add Contact to the campaign which consists of 2 actions: sending an email and remove contact with a delay between them.
Do not use ExM for this task. If you removing contact right after sending an email, it sounds like you don't really need all ExM features. And that is why you probably may not need to use ExM for sending an email. You can use built-in .Net SmtpClient to send emails.
|
Send email to contact before deleting the contact
We are adding Contact and sending email in Sitecore 9.1.1. We dont want to show that contact in Experience profile so we are deleting that contact on same method after sending email. However, log file showing the below error :
WARN Unhandled exception thrown while processing task '0xB18D3ABA71473240B0D4C6B889600324' from task pool 'dispatch_failed_task_pool'. The task has not reached the maximum number of attempts to process a failing task and is postponed.
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: contact
Source: Sitecore.Kernel
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.EmailCampaign.Cm.Pipelines.UpdateUndeliveredCount.UpdateBounceCount(HandleMessageEventPipelineArgs args, Contact contact)
at (Object , Object )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
at Sitecore.Modules.EmailCampaign.Core.PipelineHelper.RunPipeline(String pipelineName, PipelineArgs args)
at Sitecore.EmailCampaign.Cm.Tasks.MessageEventBaseTaskProcessor.OnProcess(ShortRunningTask task, CancellationToken cancellationToken)
at Sitecore.ExM.Framework.Distributed.Tasks.Processing.ShortRunning.TaskProcessor.Process(ShortRunningTask task, CancellationToken cancellationToken)
at Sitecore.ExM.Framework.Distributed.Tasks.Processing.ShortRunning.DatabaseTaskAgent.ProcessTask(DatabaseTaskDtoCollectionItem taskDto, CancellationToken cancellationToken)
When we are adding breakpoint in the code there and wait for few second then we are getting email and contact removed code working fine. Only issue here we need to send email as well before deleting that contact.
We are using the below code for sending the email :
var message = new AutomatedMessage();
message.ContactIdentifier =contact;
message.MessageId = messageId;
message.TargetLanguage = Sitecore.Context.Language.Name;
clientApiService.SendAutomatedMessage(message);
For deleting contact details we are using the below code :
var reference = new Sitecore.XConnect.IdentifiedContactReference(source, identifier);
Contact contact = client.Get<Sitecore.XConnect.Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { });
client.ExecuteRightToBeForgotten(contact);
client.Submit();
Could someone suggest me how can we achieve this functionality?
| |
I think this processor was added only for sitecore 8 because the asp.net request validation has been changed in .NET 4.0 and it was breaking the content editor, if you take a look at the current implementation you'll see that this processor is introduced for this:
Suppresses the form validation excheption that has been introduced in .NET 4.0 for Sitecore backend.
Please also take a look at the post https://stackoverflow.com/questions/9114276/request-validation-how-and-why-is-it-disabled-in-sitecore and the sitecore KB article https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0031258.
However this processor is disabling completely the validation and if you would write cross site queries like ?<script>alert('attack');</script> the page would still load normally. To fix this you would have needed to override the processor like described here https://www.loic-rabehaja.com/sitecore-blog/2015/6/2/prevent-xss-attack-on-sitecore-cms-use-of-in-built-net-validation. Hence it was removed in newer sitecore versions and I wouldn't recommend to preserve this functionality after you upgrade.
If you need to disable the request validation I think you should try to handle it at the page level instead of the whole website.
|
In Sitecore 9.3, SuppressFormValidation is not available, what is the replacement?
We are upgrading from Sitecore 8.2 to 9.3.
In our 8.2 solution, there is a patch created with the type SuppressAdfsFormValidation
<sitecore>
<pipelines>
<preprocessRequest>
<processor patch:instead="*[@type='Sitecore.Pipelines.PreprocessRequest.SuppressFormValidation, Sitecore.Kernel']" type="Sample.Pipelines.PreprocessRequest.SuppressAdfsFormValidation, Sample" />
</preprocessRequest>
</pipelines>
</sitecore>
which inherits PreProcessRequestProcessor and here is the implementation provided below:
public class SuppressAdfsFormValidation : PreprocessRequestProcessor
{
public override void Process(PreprocessRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
try
{
new SuppressFormValidation().Process(args);
}
catch (HttpRequestValidationException)
{
string rawUrl = args.HttpContext.Request.RawUrl;
if (!rawUrl.Contains("sample item") && !rawUrl.Contains("secure") && !rawUrl.Contains("login"))
{
throw;
}
}
}
}
We could not find the SuppressFormValidation() in
Sitecore.Kernel.dll(14.0.0.0) -> Sitecore.Pipelines.PreProcessRequestProcessor
Could you please suggest if there is any alternative to implement this feature?
| |
If you want to display content of a Rich Text field in WebForms, you can use:
<sc:FieldRenderer FieldName="Text" runat="server" />
or
<sc:Text Field="Text" runat="server" />
or
litText.Text = FieldRenderer.Render("Text"); // in code behind
Sitecore documentation: Access a field using the FieldRender
More information about field renderer and supported fields: Which Sitecore fields can be rendered using a FieldRenderer
|
How do I display the RTE/ Word Content in Asp.net webforms?
We have bee using Sitecore 8.1 and in 8.1 we use the Field Types RTE and Word more . Due to some reason i had to use Asp.net Webforms not MVC. Can any one please help me how do i dispay the content of RTE and Word in Webforms ?
| |
There are two options, you can create a patch for the configuration file to update the layoutService serializationMaxDepth, but this will affect all the Items:
<configuration>
<sitecore>
<settings>
<layoutService>
<serializationMaxDepth>2</serializationMaxDepth>
</layoutService>
</sitecore>
</configuration>
Or you can create your custom field serialization resolver.This class will add the information to the field:
public class CustomFieldSerializer : BaseFieldSerializer
{
public CustomFieldSerializer (IFieldRenderer fieldRenderer)
: base(fieldRenderer)
{
}
protected override void WriteValue(Field field, JsonTextWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(field.Name);
writer.WriteValue("Your custom field value here.");
writer.WriteEndObject();
}
}
This class will be the field resolver:
public class GetCustomFieldSerializer : BaseGetFieldSerializer
{
public GetCustomFieldSerializer(IFieldRenderer fieldRenderer)
: base(fieldRenderer)
{
}
protected override void SetResult(GetFieldSerializerPipelineArgs args)
{
Assert.ArgumentNotNull((object)args, nameof(args));
args.Result = new CustomFieldSerializer(this.FieldRenderer);
}
}
And this is the configuration patch to set the resolver class to your field. Make sure to place your config(patch:before) before the field default serialization configuration, in this case the multililist is GetMultilistFieldSerializer you can check this in https:///sitecore/admin/showconfig.aspx:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<group groupName="layoutService">
<pipelines>
<getFieldSerializer>
<processor patch:before="processor[@type='Sitecore.LayoutService.Serialization.Pipelines.GetFieldSerializer.GetMultilistFieldSerializer, Sitecore.LayoutService']" type="Foundation.FieldSerializer.GetCustomFieldSerializer, Foundation.LayoutService" resolve="true">
<FieldTypes hint="list">
<fieldType id="1">multilist</fieldType>
</FieldTypes>
</processor>
</getFieldSerializer>
</pipelines>
</group>
</pipelines>
</sitecore>
</configuration>
|
JSS Limit depth of items retrieved in linked fields
I have an App Route A for a page and is loading all the fields including a multilist that links to Item App Route B that can have in the multilist a link to Item A, creating a infinite loop. Is there a way to set the depth to only one level?
AppRoute A:
fields:
multifield:
AppRoute B
AppRoute B:
fields:
multifield:
AppRoute A
| |
I normally replace a Sitecore processor with a custom one using patch:instead rule. Example:
<processor type= "[custom type]" patch:instead="processor[@type='[sitecore type]']"/>
The solution for patch:attribute should be (use value for your custom type):
<processor type="[sitecore type]">
<patch:attribute name="type" value="[custom type]" />
</processor>
Also, please make sure you have the patched config only once under App_Config folder. I was able to reproduce your problem by having a copy of Project.HtmlCache.RenderRendering.config in another folder under App_Config.
|
Config patch with patch:attribute results in a duplicate setting
I am trying to patch the GenerateCacheKey processor of the mvc.renderRenering pipeline and for some reason my patch modifies the original processor (expected) but also adds a duplicate processor at the end of the pipeline section (unexpected). I'm using Sitecore 9.2.0 and my patch details are
Project.HtmlCache.RenderRendering.config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<mvc.renderRendering>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.GenerateCacheKey, Sitecore.Mvc" resolve="true">
<patch:attribute name="type">MySolution.Project.HtmlCache.Pipelines.RenderRendering.GenerateCacheKey, MySolution.Project</patch:attribute>
</processor>
</mvc.renderRendering>
</pipelines>
</sitecore>
</configuration>
Which results in the configuration (seen in ShowConfig.aspx)
<mvc.renderRendering patch:source="sitecore.mvc.config">
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.InitializeProfiling, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.StartStatisticRecording, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.ResolveArea, Sitecore.Mvc">
<param type="Sitecore.Mvc.Pipelines.Response.RenderRendering.ChainedAreaResolveStrategy, Sitecore.Mvc" desc="areaResolver">
<Resolvers hint="list">
<resolver type="Sitecore.Mvc.Pipelines.Response.RenderRendering.RenderingDefinitionAreaResolveStrategy, Sitecore.Mvc"/>
<resolver type="Sitecore.Mvc.Pipelines.Response.RenderRendering.RenderingParametersAreaResolveStrategy, Sitecore.Mvc"/>
<resolver type="Sitecore.Mvc.Pipelines.Response.RenderRendering.RenderingLayoutAreaResolveStrategy, Sitecore.Mvc"/>
</Resolvers>
</param>
<param type="Sitecore.Mvc.AreaNamespaceRegistry, Sitecore.Mvc" desc="areaNamespaceRegistry"/>
</processor>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.SetCacheability, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.EnterRenderingContext, Sitecore.Mvc"/>
<processor type="Spe.Integrations.Processors.ScriptedRenderRendering, Spe" patch:source="Spe.config"/>
<processor type="MySolution.Project.HtmlCache.Pipelines.RenderRendering.GenerateCacheKey, MySolution.Project" patch:source="Project.HtmlCache.RenderRendering.config"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.RenderFromCache, Sitecore.Mvc" resolve="true"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.StartRecordingOutput, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.ExperienceEditor.Pipelines.Response.RenderRendering.AddWrapper, Sitecore.Mvc.ExperienceEditor" resolve="true" patch:source="sitecore.mvc.experienceeditor.config"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc">
<param type="Sitecore.Mvc.Pipelines.Response.RenderRendering.HttpExceptionWrappingRendererErrorStrategy, Sitecore.Mvc" desc="rendererErrorHandler">
<param type="Sitecore.Mvc.Pipelines.Response.RenderRendering.ChainedRendererErrorStrategy, Sitecore.Mvc" desc="rendererErrorHandler">
<Handlers hint="list">
<handler type="Sitecore.Mvc.Pipelines.Response.RenderRendering.PageModeRenderingErrorStrategy, Sitecore.Mvc"/>
</Handlers>
</param>
</param>
</processor>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.AddRecordedHtmlToCache, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.RecordStatistic, Sitecore.Mvc"/>
<processor type="MySolution.Project.HtmlCache.Pipelines.RenderRendering.GenerateCacheKey, MySolution.Project" patch:source="Project.HtmlCache.RenderRendering.config"/>
</mvc.renderRendering>
Edit
As Alina Fodor mentioned in her answer, duplicate settings should only happen if there is a spurious config file lying around. In my case, this was due to a stale config file remaining in my docker container which was no longer in the solution (most likely renamed/moved).
| |
You shouldn't use Dictionary entries for this type of content. Dictionary phrase is versioned field which means you need to copy these values for every single language, and when it is changed you need to change it everywhere (applies when you don't have language fallback in place).
You have four options:
Having these values hard coded in code in some static .cs files as constants - IMHO not recommended option as changing means code change and deployment
Having these link value in config files as elements so they are easily changeable via config entries - be honest - how often these paths will be changed? - good option as it doesn't involve big overhead and no deployment is needed, however content editors and devops need to be aligned when the new content is published so at the same time also configs are changed -> this option however means restart of web app when config is changed
Having template with broad list of Link field type fields on Site level where content editors need to specify new path to that particular functionality -> Good option but needs involvement from content editors and it has additional step for them. Also publishing is needed.
Looking up pages based on template type. You will use SOLR to find pages based on specific template. The most content editor friendly (no additional work for them) and no devops involvement -> IMHO best option.
|
Storing paths to pages in Sitecore
We are using dictionaries in our project for adding static values from the code.
For example :
string path="sitecore/content/home/ContactUs"
instead of path using dictionary and passing dictionary value to path
string path=Sitecore.Globalization.Translate.Text("path")
We have path in static value. We have two option here :
Add value in constant .cs file and get that value from here.
Use Sitecore dictionary.
We are adding values in dictionaries so if we need to change there we can easily change from Content Editor without updating the code.
Can we use dictionary in this way in Sitecore?
Could someone suggest what is the correct way for adding static value in Sitecore if we change it after some time ?
| |
I faced a similar issue in the Sitecore 10 installation.
Solution - Check if the application identity user and password are correct in IIS. Check the password for your CSFndRuntimeUser user in Deploy-Sitecore-Commerce.ps1 file. In my case I installed Sitecore 9.0.2 commerce on my local as well, so I had this user already created, so I changed my password like below
The user name for a local account to be set up for the various
application pools that are created as part of the deployment.
[string]$UserName = "CSFndRuntimeUser",
# The password for the $UserName.
[string]$UserPassword = "12345",
After doing the above change I Uninstall Sitecore Commerce and Install it again.
For more details follow the blog - https://sitecorerocksblog.wordpress.com/2020/09/16/errors-during-sitecore-commerce-10-installation/
|
Sitecore commerce 10.1 installation error 503 service is unavailable
While installing Sitecore 10.1 commerce.
I am getting attached error “HTTP 503” The Service is unavailable
The above error came while the script attempts to call
BootStrapping Commerce Services: https://commerceops.sc.com/commerceops/Bootstrap()
VERBOSE: POST https://commerceops.sc.com/commerceops/Bootstrap() with 0-byte payload
I have validated every single prerequisite and can confirm that all required pre steps are done, but still getting this error.
Can you please suggest what I am missing here
| |
I don't know what's the original reason of that error but that's a long known issue with Sitecore and Solr and Docker.
You can read a thread here https://github.com/Sitecore/docker-images/issues/182 . It started in Dec 2019 and issue is still not fixed in Jan 2021.
Is there any solution? It's not really solution but workaround: change isolation level from process to hyperv for the solr service (at minimum).
So either update your .env file:
ISOLATION=hyperv
Alternatively set the solr service to run in hyperv in the docker-compose.yml or docker-compose.override.yml file.
solr:
isolation: hyperv
image: ${SITECORE_DOCKER_REGISTRY}nonproduction/solr:8.4.0-${SITECORE_VERSION}
ports:
- "8984:8983"
volumes:
- type: bind
source: .\solr-data
target: c:\data
environment:
SOLR_MODE: solrcloud
|
Solr intermittently failing with "java.nio.file.NoSuchFileException"
I have a vanilla Sitecore 10.1 SXA setup on Docker. And for all intents and purposes it functions fine.
However. Sometimes, and I've not been able to track down when or why this happens exactly, Solr "falls over" and starts giving the below exception when I try to rebuild indexes. Once this state is reached, nothing I do seems to be able to bring it back to life.
The only "fix" I've found at this stage is taking down the containers, deleting /data/solr and bringing the containers back up again (forcing the internal initialization). Once done I can populate the schema again, rebuild the indexes, and everything is fine. Until it falls over again for some unknown reason.
I am not deploying anything custom to Solr, in fact I do nothing to Solr at all. It just falls over.
Here's the exception:
Job started: Index_Update_IndexName=sitecore_core_index|#Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> SolrNet.Exceptions.SolrConnectionException: <?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader">
<int name="status">500</int>
<int name="QTime">21</int>
</lst>
<lst name="error">
<str name="msg">C:\data\sitecore_core_index_shard1_replica_n1\data\index\pending_segments_6 -&gt; C:\data\sitecore_core_index_shard1_replica_n1\data\index\segments_6</str>
<str name="trace">java.nio.file.NoSuchFileException: C:\data\sitecore_core_index_shard1_replica_n1\data\index\pending_segments_6 -&gt; C:\data\sitecore_core_index_shard1_replica_n1\data\index\segments_6
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:301)
at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287)
at java.nio.file.Files.move(Files.java:1395)
at org.apache.lucene.store.FSDirectory.rename(FSDirectory.java:302)
at org.apache.lucene.store.NRTCachingDirectory.rename(NRTCachingDirectory.java:167)
at org.apache.lucene.store.LockValidatingDirectoryWrapper.rename(LockValidatingDirectoryWrapper.java:56)
at org.apache.lucene.index.SegmentInfos.finishCommit(SegmentInfos.java:797)
at org.apache.lucene.index.IndexWriter.finishCommit(IndexWriter.java:3486)
at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:3453)
at org.apache.lucene.index.IndexWriter.commit(IndexWriter.java:3410)
at org.apache.solr.update.DirectUpdateHandler2.commit(DirectUpdateHandler2.java:678)
at org.apache.solr.update.processor.RunUpdateProcessor.processCommit(RunUpdateProcessorFactory.java:102)
at org.apache.solr.update.processor.UpdateRequestProcessor.processCommit(UpdateRequestProcessor.java:68)
at org.apache.solr.update.processor.DistributedUpdateProcessor.doLocalCommit(DistributedUpdateProcessor.java:1079)
at org.apache.solr.update.processor.DistributedZkUpdateProcessor.processCommit(DistributedZkUpdateProcessor.java:220)
at org.apache.solr.update.processor.LogUpdateProcessorFactory$LogUpdateProcessor.processCommit(LogUpdateProcessorFactory.java:160)
at org.apache.solr.handler.loader.XMLLoader.processUpdate(XMLLoader.java:281)
at org.apache.solr.handler.loader.XMLLoader.load(XMLLoader.java:188)
at org.apache.solr.handler.UpdateRequestHandler$1.load(UpdateRequestHandler.java:97)
at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:68)
at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:211)
at org.apache.solr.core.SolrCore.execute(SolrCore.java:2596)
at org.apache.solr.servlet.HttpSolrCall.execute(HttpSolrCall.java:799)
at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:578)
at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:419)
at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:351)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1602)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1711)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1347)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1678)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1249)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:220)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:152)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:335)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:505)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:370)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:267)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)
at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:781)
at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:917)
at java.lang.Thread.run(Thread.java:748)
</str>
<int name="code">500</int>
</lst>
</response>
Looking at the Solr logs, this is what I see.
Time (Local) Level Core Logger Message
5/18/2021, 8:45:06 AM
WARN false
SolrResourceLoader
Solr loaded a deprecated plugin/analysis class [solr.SynonymFilterFactory]. Please consult documentation how to replace it accordingly.
5/18/2021, 8:45:23 AM
WARN false
x:sitecore_core_index_shard1_replica_n1
UpdateLog
Starting log replay tlog{file=c:\data\sitecore_core_index_shard1_replica_n1\data\tlog\tlog.0000000000000000006 refcount=2} active=false starting pos=0 inSortedOrder=false
5/18/2021, 8:45:23 AM
ERROR false
x:sitecore_core_index_shard1_replica_n1
UpdateLog
Replay exception: final commit.
| |
To enable the Microsoft login, you just need the client id & secret. And put the follwing json settings in ExternalAuthenticationProviders.
"microsoft": [
{
"authentication_mode": "Passive",
**"client_id": "<client id>",**
**"client_secret": "<client secret>",**
"email_claim_type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"external_user_creation_url": "",
"is_enabled": true,
"messages": {
"signIn": "Microsoft Sign In",
"signInDescription": "",
"signInTitle": "Microsoft Sign In"
},
"provider_name": "Microsoft",
"username_claim_type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
}
]
And make sure the AutoCreateUsers & EnableCredentialless is true.
|
Sitecore Content Hub Azure Active Directory Login
I am trying to implement Azure AD in my Content Hub portal. I have created the App in Azure Active Directory and also add the Application ID URI, federation metadata & get the Entity Id.
In my Content Hub portal, I have updated the ExternalAuthenticationProviders.saml and saved the same.
"ExternalAuthenticationProviders": {
"global_username_claim_type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"global_email_claim_type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",
"saml": [
{
"metadata_location": "https://login.microsoftonline.com/<id>/federationmetadata/2007-06/federationmetadata.xml",
"sp_entity_id": "api://<id>",
"idp_entity_id": "https://sts.windows.net/<id>/",
"password": null,
"certificate": null,
"binding": "HttpRedirect",
"authn_request_protocol_binding": null,
"is_enabled": true,
"provider_name": "SamlNewLocal",
"messages": {
"signIn": "Azure AD",
"signInDescription": "Azure AD",
"signInTitle": "Azure AD"
},
"authentication_mode": "Active"
}
]
}
After this, I can do the login using the admin (my own email id) successfully. But the problem is I am not able to log in with other users.
Getting the below error from Content Hub:
Need your help on this, I have also enabled EnableRegister to true for new users. The domain I am using is user@<my domain>.onmicrosoft.com (Free AD).
Can anyone please highlight any point or any configuration?
| |
That setting is not related to Sitecore Experience Forms.
It's a very old setting (originating in Sitecore 7) which is not well documented and (at least to my knowledge) not used commonly:
<!-- MVC DEFAULT FORM CONTROLLER NAME
Name of the default controller to invoke when handling form posts from renderings.
An empty value means that renderings that contain empty Form Controller fields cannot handle form posts.
Default value: ""
-->
<setting name="Mvc.DefaultFormControllerName" value="" />
It seems like if:
you have a <form> tag in your rendering
you don't specify any controller (action?) for the form
and you set that setting value to some controller
Controller from the setting will be used for handling the form.
|
Mvc.DefaultFormControllerName - What does this setting do?
Using sitecore 9.3...
Im looking to override the Sitecore Experience Forms controller. I saw this setting (Mvc.DefaultFormControllerName) and was thinking I could just replace the value of this setting (The default value is "") and it would fire my controller instead of Sitecore's, but no luck. I tried just the controller name (without the word 'controller') and also the fully qualified name of the controller.
What does this setting do? Is it really for overriding the Experience Forms controller?
How do I use this setting?
| |
You can potentially replace controller used by Sitecore Experience Forms by adding a patch file which changes implementationType for serviceType="Sitecore.ExperienceForms.Mvc.Controllers.FormBuilderController, Sitecore.ExperienceForms.Mvc" service.
Original service is registered in App_Config\Sitecore\ExperienceForms\Sitecore.ExperienceForms.Mvc.config config
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore role:require="Standalone or ContentManagement or ContentDelivery">
<services>
<register
serviceType="Sitecore.ExperienceForms.Mvc.Controllers.FormBuilderController, Sitecore.ExperienceForms.Mvc"
implementationType="Sitecore.ExperienceForms.Mvc.Controllers.FormBuilderController, Sitecore.ExperienceForms.Mvc" />
</services>
</sitecore>
</configuration>
I'm not sure if that's the best idea though. It's there for security reason
|
How do I add an Anti Forgery Token and a CDN
Using Sitecore 9.3...
We are using a CDN to fully cache the entire HTML of the page. This is causing a problem with Experience Forms and the AntiForgeryToken. The value of the token gets cached. Then I submit the form and it fails antiforgery validation. I am pursuing two avenues of resolution, so far I have not been able to resolve either, but still working:
Ajax in the value of the token - Microsoft's method for generating this token is public.
This works locally, have yet to test on the CDN
Replace the Experience Forms controller - Create a custom controller thats a copy of Sitecore's but remove the request validation token check.
How would I replace this? Can I override the route: /formbuilder by setting it last, ensuring it used my route?
| |
The Container component is not a Variant component, so you can't create variants for it.
You have 2 options, the best as has already been mentioned, just add a Style option for the Container component and use that to add the background colors. It's the simplest and easiest to use option for content authors.
The 2nd is to clone an existing variant component, something like the Promo, and create your rendering variants with a placeholder for the content. This will give you the ability to have multiple rendering variants, but you will end up with a very heavy handed component for something as simple as a Container
To add a placeholder to a Rendering Variant, you can either use the Variant Placeholder item, if you are building the variant via the item model. Or, if you are using scriban templates, you can use {sc_placeholder "myPlaceholderKey"}.
As to your question about the Datasource item and cloning the Page Content component. For a component that is only there to act as a container, it is unlikely you would require a datasource item. However, the Page Content component does not use a datasource item, it uses the current context item. So {i_item} is your page item, and you would be able to render any fields on your page template.
|
Sitecore container with variants to change background color
I'd like to build a component in Sitecore that I can drag other components into when using Experience Accelerator, just like the out of the box container component. I'd also like to add variants on that component for so the user can select a different variant and that will change the background image or color of the container.
This seems like a pretty simple task, but I'm not sure where to start. So far, I have cloned the Page Content component. I was going to start with a Scriban variant, but I'm not sure if that's necessary to use Scriban? If I use Scriban, what do I use for the datasource?
| |
Welcome to Sitecore Stack Exchange. You should start by looking at the sitecore training options listed on the documentation page https://www.sitecore.com/knowledge-center/getting-started/training and also at the official courses available on https://learning.sitecore.com/. After you enlist to the certification you'll also get some training questions and topics that will be covered during the exam.
In order to pass the sitecore certification make sure you are proficient in covering all areas of the exam competencies which are described https://learning.sitecore.com/exam/sitecore-experience-solution-9-developer-certification-1. For this you would need to either cover them through the online training courses or by having experience working as a Sitecore developer as listed in the prerequisites for the exam.
If you are planning on learning sitecore and becoming a developer please take a look at the post How can I get started learning Sitecore? and https://www.sitecore.com/knowledge-center/getting-started/developing-on-sitecore.
|
Is it possible to get access to training materials for Sitecore® Experience Solution 9 Developer Certification?
I want to prepare for the Sitecore® Experience Solution 9 Developer Certification. However, I can't find anywhere some training courses, notes, or any material which will help with the preparation.
I did find some links but they were returning 404. Thus, do you guys know if there are any materials available for such preparation or it's not at all?
Thanks in advance!
| |
Here is the code which should work for you:
private Contact GetExistingXConnectContact()
{
if (!Sitecore.Analytics.Tracker.Current.Contact.IsNew)
{
var anyIdentifier = Sitecore.Analytics.Tracker.Current.Contact.Identifiers.FirstOrDefault();
if (anyIdentifier != null)
{
using (XConnectClient client = Sitecore.XConnect.Client.Configuration
.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
return client.Get(
new IdentifiedContactReference(anyIdentifier.Source, anyIdentifier.Identifier),
new ContactExpandOptions(PersonalInformation.DefaultFacetKey));
}
catch (Exception exc)
{
// handle exc
}
}
}
}
return null;
}
You can find more in Sitecore documentation, e.g. https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/set-contact-facets-in-session.html
|
xDB Xconnect.Contact returning null value
I am working with xDB code upgrade from Sitecore 8.2 to 9.3 xconnect. I'm using the below code in 8.2 to get current contact and it returning contact value.
Public Contact Getcurrentcontact()
{
return Tacker.Current.Session.Contact
}
To do the same in Sitecore 9.3 I am using the below code to get contact by contact id but it always returns the null value.
public Contact GetCurrentContact()
{
if (Tracker.IsActive && Tracker.Current != null && Tracker.Current.Session != null)
{
Contact contact = null;
Guid identifier = Tracker.Current.Contact.ContactId;
ContactReference reference = new ContactReference(identifier);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
contact = client.Get<Contact>(reference,
new ContactExpandOptions(PersonalInformation.DefaultFacetKey,
EmailAddressList.DefaultFacetKey));
}
return contact;
}
return null;
}
Can someone please help.
| |
From the question, I can see that there is no existing implementation for your requirements. So there is no anyway for you, you need to write Sitecore code. Here the Link field is a General Link field and it does not accept any image in it, you need a separate image field for the social media Icons, although there are multiple ways to handle it using CSS as well. but having an image field is always a good option.
Update-
So far what you did is almost correct, but it will require updating the code as well in the .cs file or/and .cshtml view file to render the image in between anchor tag.
|
Sitecore 9 CMS - Add an Image to a Link in the Footer
A client is using Sitecore 9 - we are not Sitecore developers.
We've been asked a simple thing: add social media links to the Footer of their Sitecore site.
Its proving more difficult than expected.
I've added the links on other pages by editing the HTML directly via the WYSWIG editor.
But the Footer appears more restricted, only accepting the addition of templates like 'Link'.
The 'Link' template has an option to add an external URL but doesn't have an option to add an image.
The CMS looks like this:
Is there any way to add a link, with an image, via the CMS (without the need to write Sitecore code), so the page chnages from this:
to this:
UPDATE 21.05.21
I've now figured out how to create my own template which, seemingly, does what I want: A Link field + an image field + an extra text field
Here is the instance of the User Defined Template, which is 'inherited' from the 'General Link' template:
However, the CMS refuses to render the sections of the User Defined Template i.e. the Image and Text fields. My guess is: the containing folder is a "Link Menu" instance and Sitecore appears to only render "Link Menu Items". For example, I added a standard "Button" instance under that folder...and that doesn't render either.
Screenshot of the rendered page:
And the markup clearly shows that the new Template renders but the extra fields do not:
Can anyone help me understand why the extra fields in my template don't render?
| |
It's because, the registration of IClientApiService is in the \App_Config\Sitecore\EmailExperience\Sitecore.EmailExperience.ContentDelivery.config file which has a role constraint - role:require="Standalone or ContentDelivery".
The following lines are responsible to register the IClientApiService (and some others):
<services>
<!-- Configurator used by EXM to register required services -->
<configurator type= "Sitecore.EmailCampaign.Cd.DependencyInjection.CustomServiceConfigurator, Sitecore.EmailCampaign.Cd"/>
</services>
If you need this on CM, you need to patch this configuration by using the ContentManagement role.
|
IClientApiService is null if server role is CM
We are adding contact on Email subscription.
IClientApiService _clientApiService = ServiceLocator.ServiceProvider.GetService<IClientApiService>();
_clientApiService.UpdateListSubscription(new UpdateListSubscriptionMessage()
{
ListSubscribeOperation = ListSubscribeOperation.Subscribe,
ContactIdentifier = contact.Identifiers.FirstOrDefault(),
MessageId = Guid.Parse(id),
ManagerRootId = Guid.Parse(managerRootId),
RequireSubscriptionConfirmation = true,
});
However, this code is working fine on Standalone role but when we are using this code on CM role then we are getting null in _clientApiService and it is throwing an error.
I am using Sitecore version 9.1.1.
| |
You don't need to explicitly convert Sitecore.Tracking.Analytics.Contact to XConnect.Contact as this is done on session end where data collected by the tracker is converted. You can take a look at the conversion pipelines described here https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/conversion-pipelines.html, which are also responsible for loading existing contacts into tracker.
XConnect.Contact is used to save/load contact data to xConnect as shown on the diagram https://doc.sitecore.com/developers/93/sitecore-experience-platform/en/tracking-and-xconnect.html.
The Sitecore Tracker uses Sitecore.Analytics.Tracking.Contact to track and identify contacts and their interactions during their visit to the CD instance, it does not use the xConnect model. You should use this model if you wish to modify the contact values in session before being saved into xDB.
|
Sitecore.XConnect.Contact vs Sitecore.Analytics.Tracking.Contact
I am upgrading code from Sitecore 8.2 to Sitecore 9.3.
In Sitecore 8.2 we have a code snippet:-
public Contact GetCurrentContact()
{
if (Tracker.IsActive && Tracker.Current != null && Tracker.Current.Session != null)
{
return Tracker.Current.Session.Contact;
}
return null;
}
public Contact IdentifyContact(global::Sitecore.Security.Accounts.User user)
{
if (user == null)
return null;
string contactIdentifier = GetContactIdentifier(user);
if (string.IsNullOrEmpty(contactIdentifier) || contactIdentifier.Contains("anonymous") || Tracker.Current == null || Tracker.Current.Session == null)
{
return null;
}
Tracker.Current.Contact.Identifiers.AuthenticationLevel = AuthenticationLevel.PasswordValidated;
Tracker.Current.Session.Identify(contactIdentifier);
return Tracker.Current.Contact;
}
In this Sitecore 8.2 Contact object is coming from Sitecore.Analystics.Tracking but in Sitecore 9.3 do you need to convert Contact to Sitecore.XConnect.Contact?
Contact contact = _contactProvider.GetCurrentContact();
DocLanguageAndRegionPreferences docPreferences;
_contactRepository.SetDocumentLanguageAndRegionPreference(contact, docPreferences);
I have another class using this contact to add item to facet and then communicating with Xdb in Sitecore 8.2
public void SetDocumentLanguageAndRegionPreference(Contact contact, DocLanguageAndRegionPreferences docPreferences)
{
if (contact == null)
return;
IFacetData facet = contact.GetFacet<IFacetData>(FacetData.FacetName);
if (docPreferences.Languages != null && docPreferences.Languages.Any())
{
foreach (var language in docPreferences.Languages)
{
var docLanguage = facet.FacetCentralData.Preferences.DocumentLanguageFilters.Create();
docLanguage.Language = language;
}
}
}
This is Sample code of that class.
Facet is working fine, just have some doubt.
In this class also I am getting parameter contact in form on Sitecore.Tracking.Analytics.Contact. How can I convert this contact to XConnect.Contact for Sitecore 9.3?
| |
You need to define
Final Confirmation Page - The page displayed after a visitor changes their subscription:
on your EXM Manager Root item.
Then Sitecore will redirect you to that page after subscription confirmation.
|
Error when click on Subscription confirmation link
Using the below mentioned code for adding contact in List manager using EXM in SXA Sitecore 9.1.1.
public ISubscriptionManager SubscriptionManager { get; }
public EmailSubscriptionRepository(ISubscriptionManager subscriptionManager)
{
SubscriptionManager = subscriptionManager;
}
After injecting this we are using below code
SubscriptionManager.Subscribe(contact.Identifiers.FirstOrDefault(), Guid.Parse(emailCampaignId), true);
This code is working fine and sending a Subscription confirmation email but when we click on the link which is mentioned in the mail it stuck on below url
https://domainname/sitecore%20modules/Web/EXM/ConfirmSubscription.aspx?ec_subscr=9J6G6D2D2184B60B6E00A8ECE41RFED
| |
We added phoneNumber in CommerceUser, for that we used below code. You can update as per your requirement. But yes you need to save it into Customer Entity using below code.
public bool UpdateAccountPhone(string phone, IContext sitecoreContext)
{
bool result = false;
// Update phone number
CustomerServiceProvider customerProvider =
(CustomerServiceProvider)Factory.CreateObject(nameof(customerProvider), true);
var commerceUser = this.GetCommerceUser(sitecoreContext);
if (commerceUser != null)
{
commerceUser.SetPropertyValue("Phone", phone);
// Update the user
var updateRequest = new UpdateUserRequest(commerceUser);
customerProvider.UpdateUser(updateRequest);
result = true;
}
return result;
}
Use namespace below
using Sitecore.Commerce.Services;
using Sitecore.Commerce.Services.Customers;
Then you can get property like below -
commerceUser.GetPropertyValue("Phone").ToString();
|
What is the correct way to set commerce user custom profile properties
I'm trying to set & get the custom property values for a commerce user.
While fetching the value, there is an error:
The given key was not present in the dictionary
public void SetCommerceUserProfilePropertyValues(string usernameWithDomain, List<KeyValuePair<string, object>> keyValuePairs)
{
if (keyValuePairs != null && keyValuePairs.Count > 0)
{
Sitecore.Commerce.Entities.Customers.CommerceUser commerceUser = GetCommerceUser(usernameWithDomain);
if (commerceUser != null)
{
foreach (KeyValuePair<string, object> kvp in keyValuePairs)
{
commerceUser.SetPropertyValue(kvp.Key, kvp.Value);
}
}
}
}
public object GetCommerceUserProfilePropertyValue(string usernameWithDomain, string propertyName)
{
CommerceUser commerceUser = GetCommerceUser(usernameWithDomain);
return commerceUser != null ? commerceUser.GetPropertyValue(propertyName) : null;
}
public void MyMethod()
{
string usernameWithDomain = "Storefront\\[email protected]";
List<KeyValuePair<string, object>> keyValuePairs = new List<KeyValuePair<string, object>> {
new KeyValuePair<string, object>("ForgotPasswordToken", Guid.NewGuid()),
new KeyValuePair<string, object>("ForgotPasswordTokenCreatedDate", DateTime.Now)
};
///save custom property values
SetCommerceUserProfilePropertyValues(usernameWithDomain, keyValuePairs);
--Exception here
var xtoken = GetCommerceUserProfilePropertyValue(usernameWithDomain, "ForgotPasswordToken") as string;
}
The commerceUser is not null and there is no error while setting the value.
Is there any "Save" action to be done just like it is done for Sitecore user profile - profile.Save()
Using XC 10.1
| |
This is how SwitchOnRebuildSolrSearchIndex solr works , this is not a bug.
Your website uses indexes from the primary core. Each time you initiate a full index rebuild, Sitecore does this in the secondary core. The secondary core then becomes the primary one after the rebuild.
You can read more about it in @Marek blog - https://www.skillcore.net/sitecore/using-switchonrebuildsolrsearchindex-solr-provider-for-sitecore and Sitecore article - https://doc.sitecore.com/developers/90/platform-administration-and-architecture/en/switch-solr-indexes.html
So that means your website will always use the primary core for results, it will switch these after the index is completed.
|
Sitecore SOLR core pointing to different core directory
I have setup the SOLR with switch on rebuild configuration. But after setting it up I am facing a weird issue like my SOLR web index core is pointing to different SOLR index directory.
Let me explain,
When I check the sitecore_web_index from the SOLR panel then I can see in the Instance section that my Sitecore secondary web index (sitecore_web_index_sec) is pointing to the main Sitecore web index (sitecore_web_index) and main Sitecore web index is pointing to the Sitecore secondary web index.
For example, you can see in the screenshot below that when I check secondary web index (red box) then it is pointing to the Sitecore main index directory data (green box).
This is vice versa (see screenshot below)
I checked the core.properties file for both web index directory. For the main Sitecore index it is as below:
#Written by CorePropertiesLocator
#Mon Apr 26 08:48:41 UTC 2021
config=solrconfig.xml
name=sitecore_web_index
schema=schema.xml
dataDir=data
and, for the Sitecore secondary web index it is as:
#Written by CorePropertiesLocator
#Mon Apr 26 08:48:41 UTC 2021
config=solrconfig.xml
name=sitecore_web_index_sec
schema=schema.xml
dataDir=data
Do you have any idea why is it happening?
| |
The call will be authenticated based on the Content Hub cookies you have. So it will use the logged in user to make the call.
You can use jQuery to make the call, the library is already loaded.
$.ajax({
url: `${options.api.entities.href}&skip=0&take=10`,
contentType: 'application/json',
type: 'get',
success: (data) => {
callback(data);
}
});
|
How to call api from external component
I am developing external component in Sitecore Content Hub 4.X. I want to call REST API as a current logged user.
Custom component expose some options, for example options.api but it is only text...
https://docs.stylelabs.com/content/4.0.x/integrations/integration-components/external-page-component/external-page-options.html?redirect=true
but how to call for example options.api.entities using credentials of already logged user?
| |
I don't think this UpdateListOperation influence your server performance.
Please have a look if you have children under the item: /sitecore/system/List Manager/ListOperations .
On the agent you have next method which run :
public void Run()
{
foreach (ListOperation operation in this._listOperationRepository.GetOperations())
{
if (operation.Status == OperationStatus.Indexing)
{
BaseJobManager jobManager = this._jobManager;
Guid id = operation.Id;
string jobName = id.ToString();
if (jobManager.GetJob(jobName) == null)
{
id = operation.Id;
this._jobManager.Start((BaseJobOptions) new DefaultJobOptions(id.ToString(), operation.OperationType, Context.GetSiteName(), (object) this, "CheckIndexing", new object[1]
{
(object) operation
}));
}
}
}
}
In your case _listOperationRepository.GetOperations() should return empty results so it takes few miliseconds to finish the Agent.
Please have a look on other things which can influence performance like DTU of the databases, sizes of app services or the custom code.
|
Increase Sitecore.ListManagement.Operations.UpdateListOperationsAgent agent run interval
Using sitecore 9.2 in azure, I am seeing in the logs for all of the environments entries related to the agent Sitecore.ListManagement.Operations.UpdateListOperationsAgent which in config by default is set to run every 10 seconds:
12:26:31.743 PM Job ended: Sitecore.ListManagement.Operations.UpdateListOperationsAgent (units processed: )
12:26:31.743 PM Job started: Sitecore.ListManagement.Operations.UpdateListOperationsAgent
12:26:21.730 PM Job started: Sitecore.ListManagement.Operations.UpdateListOperationsAgent
12:26:21.730 PM Job ended: Sitecore.ListManagement.Operations.UpdateListOperationsAgent (units processed: )
12:26:11.718 PM Job started: Sitecore.ListManagement.Operations.UpdateListOperationsAgent
12:26:11.718 PM Job ended: Sitecore.ListManagement.Operations.UpdateListOperationsAgent (units processed: )
12:26:01.699 PM Job started: Sitecore.ListManagement.Operations.UpdateListOperationsAgent
12:26:01.699 PM Job ended: Sitecore.ListManagement.Operations.UpdateListOperationsAgent (units processed: )
<scheduling>
<agent type="Sitecore.ListManagement.Operations.UpdateListOperationsAgent, Sitecore.ListManagement" method="Run" interval="00:00:10" resolve="true" />
</scheduling>
I saw various posts that were mentioning that increasing this agent to run at 30 min will speed up the local environment. I am trying to find out if the agent can affect the performance of the website in any way and if the interval should be increased in higher environments aswell.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.