output
stringlengths 34
25.7k
| instruction
stringlengths 81
31k
| input
stringclasses 1
value |
---|---|---|
Adding an answer, as this sounds very similar to a situation we faced, whereby a seemingly isolated publish (with related items) of an item led to all nodes under sitecore/content being deleted from all publishing targets.
Sitecore.Update tool
If upgrading to Sitecore 10+ from a lower version, one of the required steps in the upgrade guide is to run the Sitecore.Update tool. The reason for this is because from sitecore 10 onwards, all the important central sitecore items for core, master, web databases are stored in .dat files on disk. Because of this, the tool must be run to remove these items from the relevant databases. They are then read from disk instead of SQL.
If an item has been modified in anyway, then it is up to the person performing the upgrade to review the item, delete manually from database and then reapply the modification via sitecore UI if required. This process ensures that the most up-to-date items are used.
You can find the upgrade guide on the following page: https://dev.sitecore.net/Downloads/Sitecore_Experience_Platform/101/Sitecore_Experience_Platform_101.aspx
Our issue
When performing the above steps, it is essential that you apply the changes / deletions on all publishing targets. The issue we faced was sitecore/content or other top level items had been modified, so we deleted them from SQL (choosing not to reapply the changes). However, we did not perform the steps on two publishing targets.
Some weeks later, a publish was performed with related items checked. When publishing related items, a chain event is started, with any referenced item also being published, which can grow to a very large number of items. In our case, this also included the root sitecore/content.
At this point, a comparison was made between the master DB and the publishing targets DB. Because the sitecore/content item had been deleted in the master, but not in the publishing target, a chain of delete events were registered to remove every item under that root item. Thus deleting all data from the publishing target.
You can read more about this on my blog post here:
https://deanobrien.uk/loss-of-all-content-from-our-web-databases/
Your Issue
To confirm if you are facing a similar problem, please review your web database and check to see if the /sitecore and the /sitecore/content items exist.
Look in your logs for entries like:
WARN Publish: Target item could not be deleted (/sitecore)
WARN Publish: Target item could not be deleted (/sitecore/content)
If neither of the above are true, then find the deepest item in your site tree and check if it is set to publishable.
| Smart publish wiping web database
We have an issue whereby our smart publish is wiping the web database when publish related items is checked and publish children is checked.
We have copy text components folder that is referenced in many pages, publishing this folder physically removes the pages from the web database??
I have disabled deep scan publishing for related items but this issue persists.
<!-- PUBLISHING DEEP SCAN RELATED ITEM
This setting specifies that all the subitems of the item being published are
scanned recursively for changes and that all the changed items are published.
Default vaue: true
-->
<setting name="Publishing.DeepScanRelatedItems" value="false" patch:source="Publishing.config"/>
Surely a content editor publishing a copy text folder should not result in actual pages being removed before they are updated?
I can either wait for the publish to finish and have the website's offline - not acceptable, or I am forced to restart CM server and rollback the web database to before the publish operation was triggered. What gives?
444768 14:00:00 INFO [PublishOptions]: root:{AE79738A-1682-4CD2-9615-FD37E6D19B9B}, language:en, targets:Internet, database:web, mode:SingleItem, smart:True children:True, related:True
447740 14:00:01 WARN DeepItemPublish detected. PublishContext was overridden with DisableDatabaseCaches=True.
447740 14:00:01 INFO Starting [Publishing] - AddItemsToQueue
| |
By default, the new role has read access to everything. In Sitecore, when you assign access rights to items, they always inherit the access right that is assigned to their parent item in the content tree. However, if you need to, you can overrule the inherited rights on an item by assigning access rights specifically on the item or denying the item the right to inherit.
So I'd recommend to create a new role called DenyWorkboxAccess that denies read access. Apply this role only to those content contributors who aren't allowed to perform any of the actions in the Workbox.
Follow the below steps to set up new role/permission.
Click on Role Manger from Launchpad.
Click on the New button at the top left corner of the ribbon.
Add the role name DenyWorkboxAccess and click Ok.
Find the newly created role (you can search it now using search box). Click on the role row to select it then click on Security Editor from tool group on the ribbon.
Find these items and deny the read access by clicking the X button for each item.
/sitecore/client/Applications/Launchpad/PageSettings/Buttons/ContentEditing/Workbox
/sitecore/content/Documents and settings/All users/Start menu/Programs/Workbox
/sitecore/content/Applications/Content Editor/Applications/WorkboxForm
Applied "DenyWorkboxAccess" to users.
It would look like the below screen once you deny read access.
Hope it helps!
| How Might We Hide the Workbox From Certain Users?
We have a role for content contributors who aren't allowed to perform any of the actions in the Workbox (Sitecore 9.2). To avoid confusion and mischief, we'd like to hide the Workbox from these users altogether: i.e., hide the Workbox button on the Launchpad and the links on the Content Editor and the Desktop "All Applications" menu. There's lots of information around about how to show, hide, enable and disable Workflow states, but not much about how to manipulate the Workbox, so I'm not real clear how to go about this.
| |
There are different reasons why Sitecore can always show the default variant. Fundamentally it means that either the Content Delivery server is not configured to run A/B tests or it does not know that there is a test on the page.
You can try the following steps to identify where the issue is:
The first thing to check is that these three settings are enabled in Sitecore config on the Content Delivery server: xDB.Enabled, xDB.Tracking.Enabled and ContentTesting.Enabled.
Check that you have the SC_ANALYTICS_GLOBAL cookie in the browser. Cookie consent modules and custom code can block this cookie if there is no consent given.
Another possible reason for missing analytics cookie can be lack of @Html.Sitecore().VisitorIdentification() tag in the website layout file.
Make sure that your page with the test and all relevant data sources are published to the Web database. I can see you have already tried this, but you can double check that these items are definitely updated in the Web DB.
Another important element is the test definition item, it should be located in the folder /sitecore/system/Marketing Control Panel/Test Lab, have the workflow state Deployed and published to the Web database too.
I noticed that the test definition item is not always published, even when I publish the page with related items. It may help if you try locating this item in the folder /sitecore/system/Marketing Control Panel/Test Lab and publishing it manually.
| Sitecore A/B testing always shows default variant
I am using Sitecore 9.1 update 1.
I have setup A/B testing on component level. As it has workflow, I followed the article https://doc.sitecore.com/xp/en/developers/82/sitecore-experience-platform/adding-content-testing-to-a-workflow.html and started the test using Approve with test and also published properly after it started using publish related items also.
The test shows active but it always shows default variant. The setting ContentTesting.AlwaysShowTestCandidateNotification is also true.
Can somebody suggest what could be the issue and how to fix this.
| |
This worked for me.
MyProject.Publish.wpp.targets:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<SitecoreAssembliesToExclude Include="@(SitecoreAssemblies)" />
</ItemGroup>
<ItemGroup>
<ExcludeFromPackageFiles Include="bin\Sitecore.*.dll;" Exclude="bin\Sitecore.Commerce.Proxy.dll"/>
<ExcludeFromPackageFiles Include="bin\*.dll.config;
bin\Stratum.Publish.Website.dll;
bin\Stratum.Publish.Website.pdb;
bin\de;
bin\Scriban.dll;
bin\Spatial4n.Core.dll;
bin\Newtonsoft.Json.dll;
bin\Newtonsoft.Json.Bson.dll;
bin\Microsoft.OData.Client.dll;
bin\AjaxMin.dll;
bin\Microsoft.Extensions.Caching.StackExchangeRedis.dll;
bin\HtmlAgilityPack.dll;
bin\Microsoft.Bcl.AsyncInterfaces.dll;
bin\Microsoft.Extensions.DependencyInjection.Abstractions.dll;
bin\Microsoft.Extensions.DependencyInjection.dll;
bin\Microsoft.Web.Infrastructure.dll;
bin\System.Web.Helpers.dll;
bin\System.Web.Mvc.dll;
bin\System.Web.Razor.dll;
bin\System.Web.Webpages.Deployment.dll;
bin\System.Web.Webpages.dll;
bin\System.Web.Webpages.Razor.dll;
" />
</ItemGroup>
</Project>
| Helix publishing pipeline not excluding Sitecore Assemblies
I'm trying to setup a common publish project using the Helix Publishing Pipeline.
When I publish to my local temp directory, it publishes Sitecore Assemblies and also other files like HtmlAgilitypack.dll, Newtonsoft.dll, System.Web.Helpers.dll etc.
Using Visual Studio 2019.
How can I exclude them?
Should the setting be in Local.pubxml or should it be in the .wpp.targets file?
I tried using the commented code in template - AdditionalFilesToRemoveFromTarget, <SitecoreAssembliesToExclude. None worked.
Here are my files:
Local.pubxml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>FileSystem</WebPublishMethod>
<LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<PublishUrl>C:\out\Stratum</PublishUrl>
<LaunchSiteAfterPublish>False</LaunchSiteAfterPublish>
<ExcludeApp_Data>False</ExcludeApp_Data>
<DeleteExistingFiles>False</DeleteExistingFiles>
</PropertyGroup>
<Target Name="EnsurePublishUrl" BeforeTargets="Build">
<Error Condition="'$(PublishUrl)' == ''" Text="Please configure a publishUrl in $(MSBuildProjectName)/Properties/PublishProfiles/Local.pubxml. You may need to reload your solution to apply the change.
Auto-publish can be disabled in $(MSBuildProjectName).wpp.targets." />
</Target>
</Project>
Stratum.Publish.Website.wpp.targets
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<SitecoreAssembliesToExclude Include="@(SitecoreAssemblies)" />
</ItemGroup>
<PropertyGroup>
<EnableAutoPublish>false</EnableAutoPublish>
<AutoPublish Condition="'$(AutoPublish)' == '' and '$(EnableAutoPublish)' == 'true' and '$(Configuration)' == 'Debug' and '$(BuildingInsideVisualStudio)' == 'true' and '$(PublishProfile)' != ''">true</AutoPublish>
<AutoPublishDependsOn Condition="'$(AutoPublish)' == 'true'">
$(AutoPublishDependsOn);
WebPublish
</AutoPublishDependsOn>
</PropertyGroup>
<Target Name="AutoPublish" AfterTargets="Build" DependsOnTargets="$(AutoPublishDependsOn)">
</Target>
</Project>
packages.config
<packages>
<package id="RichardSzalay.Helix.Publishing.WebRoot" version="1.5.6" targetFramework="net48" />
<package id="Sitecore.Assemblies.Platform" version="10.3.0" targetFramework="net48" />
</packages>
| |
In the Sitecore Access Viewer ribbon there is Columns button.
Click on it and check both Workflow State Delete and Workflow State Write checkboxes.
Select again access rights you want to see:
| Workflow missing from explanation panel of access viewer
Does anyone know what triggers the workflow section to appear in the explanation panel of access viewer. I have the same user account configured with the same permissions on both UAT and Production. When viewing permissions on UAT I see the workflow section, but on Production I don't. Thanks
| |
While I can't tell how you fixed it before, one option is to just force the culture settings you want in web.config.
E.g. <globalization uiCulture="es" culture="es-MX" />
Reference: https://learn.microsoft.com/en-us/previous-versions/aspnet/bz9tc508(v=vs.100)
| Set default decimal format for numbers (period instead of comma)?
I have a site whose production instance is hosted in Germany, which we are currently upgrading (8.2 to 10.1). We have decimals that are displayed on the site, and because the prod server is German the decimal separator is showing as a comma.
Yes, I know that I could format every decimal output in my code with the correct locale or convert to string and do a string replace, but we had this fixed in the old production instance (which is on the same server) and the exact same code is being used, so I'm trying to figure out how we fixed this before -- it is NOT a server setting (as it's the same server), and I shouldn't have to make any code changes since the code is outputting the correct decimal format in 8.2, so I figure there must be a Sitecore configuration setting that I'm missing.
So, how can I globally set the decimal delimiter to use a period instead of a comma?
| |
Yes you can do it by creating an API controller. So for this you need to follow these steps.
Create a controller and inherit it from ApiController
namespace Feature.ExampleApi.Controllers
{
public class ExampleApiController : ApiController
{
[HttpPost]
[Route("post/{itemNameString}")]
public IHttpActionResult CreateItem(string itemNameString)
{
// Do your operation
// Do sth with item
return Json(result);
}
}
}
Register your controller
namespace Feature.ExampleApi
{
public class ServicesConfigurator : IServicesConfigurator
{
public void Configure(IServiceCollection serviceCollection)
{
// Controllers
serviceCollection.Replace(ServiceDescriptor.Transient(typeof(ExampleApiController),
typeof(ExampleApiController)));
}
}
}
If you are working with headless environment, register it like this.
public void Configure(IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<IDefaultRenderingContentsResolver, DefaultRenderingContentsResolver>();
serviceCollection.AddMvcControllers("*.Feature");
}
Follow this article for headless environment.
https://trnktms.com/2022/09/29/sitecore-headless-how-to-reuse-layout-service-serialization-in-custom-api-controllers/
Create config.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<services>
<configurator type="Feature.ExampleApi.ServicesConfigurator, Feature.ExampleApi" />
</services>
</sitecore>
</configuration>
Follow this article for more details.
https://jakubwajs.wordpress.com/2020/06/21/create-api-controller-in-sitecore-9-3/
You can also work with the Sitecore Item Serice to create items and more.
https://doc.sitecore.com/xp/en/developers/92/sitecore-experience-manager/the-restful-api-for-the-itemservice.html
| Is there any way to expose Sitecore Api? So that 3rd party application can use POST request and further sitecore application can manage POST request
I have 3rd party application, and I want to send some data to sitecore application using POST method. So is it possible to handle HTTP POST within sitecore MVC ? If yes please suggest how to proceed
| |
You can do it by adding the validation through OnItemCreated event. Where you can specify your template name (for example Carousel) and if its child items exceed the limit then you can show the message and delete the item. The code will look like this.
public void OnItemCreated(object sender, EventArgs args)
{
var createdArgs = Event.ExtractParameter(args, 0) as ItemCreatedEventArgs;
if (createdArgs != null)
{
if (createdArgs.Item != null)
{
var item = createdArgs.Item;
if (item.Parent != null &&
item.Parent.TemplateName == "carousel" &&
item.Parent.Children.Count() > 8)
{
SheerResponse.Alert(
String.Format("Sorry, you cannot add more than 8 slides to {0}.",
item.Parent.Name), new string[0]);
// write here your logic to delete the item.
}
}
}
}
This works when you create the item from the content editor and experience editor.
Once you are done with your method then register it using a patch config like this.
<event name="item:created">
<handler type="MyProject.Sc.Extensions.Events.ItemCreatedEvent, MyProject.Sc.Extensions" method="OnItemCreated" />
</event>
It will look like this.
Hope this helps.
| Limit max number of composite components
Is there a way to limit the max number of composite items in an SXA composite component like Carousel? For example the carousel has no more then 8 slides.
It sounds like SXA does not have anything built in and I'd need to implement some sort of validation. If that is the case can anyone share an example of how to achieve that?
This is on SXA 10.2
| |
When a new Next.js app is create a default 404 Page file is created.
This file is statically generated at build time.
import NotFound from 'src/NotFound';
const Custom404 = (): JSX.Element => <NotFound />;
export default Custom404;
If we want to customize the 404 page, we have to use getStaticProps to fetch data at build time.
To fetch data during build time in Sitecore we have to customize 404.tsx file.
Inside 404.tsx we need to fetch data from _404 error page.
import { SitecorePageProps } from 'lib/page-props'
import { sitecorePagePropsFactory } from 'lib/page-props-factory'
import { GetStaticProps } from 'next'
import SitecorePage from './[[...path]]'
export const getStaticProps: GetStaticProps = async (context) => {
let props = { notFound: false }
props = await sitecorePagePropsFactory.create({
...context,
params: { ...context.params, path: '/_404' },
})
return {
props,
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 5 seconds
revalidate: 5, // In seconds
notFound: props.notFound, // Returns custom 404 page with a status code of 404 when true
}
}
export default function Custom404Page({
notFound,
layoutData,
componentProps,
navigation
}: SitecorePageProps): JSX.Element {
return (
<SitecorePage
notFound={notFound}
layoutData={layoutData}
componentProps={componentProps}
navigation={navigation}
dictionary={{}}
locale=""
/>
)
}
The SitecorePagePropsFactory class uses an instance of the ComponentPropsService class that helps to identify which components require retrieval of data. The ComponentPropsService is provided by the NPM package @sitecore-jss/sitecore-jss-nextjs.
More information can be found here: https://sitecoreclimber.wordpress.com/2021/11/21/page-not-found-in-sitecore-headless-next-js/
| How to get 404 status code on Rendering host
There is a Sitecore Headless setup with SSG enabled. NextJS allows to show own 404 page but the requirement is to managed the page in CMS.
Quick solution was to extend the getStaticProps method in [[...path]].tsx file and just redirect to the /page-not-found:
export const getStaticProps: GetStaticProps = async (context) => {
const props = await sitecorePagePropsFactory.create(context);
// HERE: Redirect to /page-not-found:
if (props.notFound) {
return {
redirect: {
permanent: false,
destination: '/' + props.locale + '/page-not-found',
},
};
}
return {
props,
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 5 seconds
revalidate: 5, // In seconds
};
};
It works but there are few drawbacks. The url in browser changes which is odd. Besides that, the page status code is 200 instead of 404 which is not correct from the SEO perspective.
In order to fix that, instead of redirect, the CM/CD HttpRequestBegin pipeline has been extended as suggested in this post and this answer. Currently, request to CM/CD Layout Service returns proper NotFound page response with all the placeholders, renderings and status code 404:
https://cd.localhost/sitecore/api/layout/render/default?item=/missing-page&sc_apikey=xxx
{
"sitecore": {
"context": {
"pageEditing": false,
"site": {
"name": "mysite"
},
"pageState": "normal",
"language": "en",
"itemPath": "/page-not-found",
},
"route": {
"name": "Page not found",
"fields": {...},
...
"placeholders": {...}
}
}
}
The page is rendered correctly with NextJS. Browser URL does not change, but the status code is still 200... Even with the 404 responce from Layout Service... How to change it to 404?
| |
pre-optimized-min items are generated automatically. Each time with new id.
When you save pre-optimized-min.yml in your source control, next time someone checks out from source control and their Sitecore generates new pre-optimized-min, it wants to serialize that new item, but it checks that there is already a file like that on the drive, so it adds guid to the file name.
Normally, when SXA deletes old 'pre-optimized-min` item, it deletes serialized item as well. But because you keep the old one in source control, there are situations that old one is still there from source control, a new one is created with guid in filename.
| Pre-optimized-min file named with GUID Sitecore SXA 10.2
We use Unicorn in our project, and we are saving the pre-optimized-min.yml files in source control. Here is the exclude predicate we have for this file:
<exclude childrenOfPath="/sitecore/media library/Themes/<Name>/<Name>/styles">
<except name="pre-optimized-min" />
</exclude>
We use a standard SXA CLI Setup.
The problem is that after minification, SOMETIMES, the yml file is saved with a GUID at the end of the name:
This is causing issues in our CI/CD pipeline as the file is not recognized and our styles are not picked up correctly.
Any ideas on this could be happening?
| |
I think your issue is the way you are adding the --config parameter, you should add the path to the folder containing sitecore.json, rather than the file itself.
Please try this instead:
dotnet sitecore publish --config .\
If you see below, I tried the same command as you did first. It gives same errors (basically saying it doesnt recognise the command as publish plugin not referenced).
The second try rerences the folder and a publish starts.
| How to publish only serialized items
How to publish only the serialized items using the Sitecore CLI command.
I have configured the Module files path in the sitecore.json file.
When I run dotnet sitecore publish, i guess it is trying to publish the whole site.
So, in order to publish only the serialized items, I have tried this command which gives an error.
dotnet sitecore publish --config .\sitecore.json
The sitecore.json file is in the project's root folder. So the path is correct. The pull & push commands are working fine.
Update 1:
When I execute dotnet sitecore publish --config .\ it says started and there is no progress for almost 30 mins and it then shows this error.
Update 2:
My sitecore.json file is in the root directory. Yet I have provided the path. There is no progress. It just says publish started. After 10 mins I have to do a CTRL + C to stop it.
Could it be because, how I have named my module files.
| |
When EXM dispatches the emails campaigns, it encrypts every link in the message body. A typical example of an encrypted link is
http://{your_website_domain}/sitecore%20modules/Web/EXM/RedirectUrlPage.aspx?ec_eq={encrypted_value}
EXM.CryptographicKey and EXM.AuthenticationKey configured in the ConnectionString.config file are used to encrypt and decrypt the query string in the email campaigns sent to the end-users. So, make sure that both keys are configured correctly.
It is important to note that the test emails don't encrypt the links!
Also I would suggest to check on modifyHyperlink pipeline configuration in Sitecore.EmailExperience.Core.config file, it is being executed for every link in an email and supplements the link URL in the email to a RedirectURL link with all required URL params. For example:
<modifyHyperlink>
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.SkipAnchorLinks, Sitecore.EmailCampaign" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.SetServerUrl, Sitecore.EmailCampaign" resolve="true" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.SkipAlreadyProcessedHyperlink, Sitecore.EmailCampaign">
<RedirectPagePath>/sitecore%20modules/Web/EXM/RedirectUrlPage.aspx</RedirectPagePath>
</processor>
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.MapHostname, Sitecore.EmailCampaign" resolve="true" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.SetAnalyticsQueryStringParameters, Sitecore.EmailCampaign" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.HandleInternalLink, Sitecore.EmailCampaign" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.GeneratePreviewLink, Sitecore.EmailCampaign" />
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.GenerateHyperlink, Sitecore.EmailCampaign">
<RedirectPagePath>/sitecore%20modules/Web/EXM/RedirectUrlPage.aspx</RedirectPagePath>
<UrlQueryKey ref="settings/setting[@name='QueryStringKey.RedirectUrl']/@value" />
</processor>
<processor type="Sitecore.Modules.EmailCampaign.Core.Pipelines.GenerateLink.Hyperlink.EncryptQueryString, Sitecore.EmailCampaign">
<param desc="queryStringEncryption" ref="queryStringEncryption" />
</processor>
</modifyHyperlink>
| ?ec_eq= query string is missing on EXM Subscriptionpreference page
I have setup EXM mails. In footer of the mail body, there is link for subscription preference /sitecore%20modules/Web/EXM/SubscriptionPreferences.ashx.
When I sent the mail to my mail id and open the mail, On clicking the subscription preference link, it should open a page with a link with querystring e.g /sitecore%20modules/Web/EXM/SubscriptionPreferences.ashx?ec_eq=0uMnA4%2ffRO2xlcZnBiklIlB%2fdKcyQGotX
This querystring is ec_eq automatically generated by Sitecore but in my case when I click on the link, it only opens the link without querystring i.e /sitecore%20modules/Web/EXM/SubscriptionPreferences.ashx
Can somebody please suggest what could be missing that the querystring is not added to the url?
In the message container setting everything looks correct. Any idea if any other setting or config I am missing?
| |
So, Dave, you're sort of right that these fields are not supported..."out of the box"? We just did this for another field type TreeList which is similar to MultiList.
You can add fields to the GraphQL service by creating a patch file to modify the Sitecore.Services.GraphQL.Content.config. Under the Content > fieldTypeMappings > inputTypeMapping section, you add mapping to another field type.
The config patch file could look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<api>
<GraphQL>
<defaults>
<content>
<fieldTypeMappings>
<inputTypeMapping type="Sitecore.Services.GraphQL.Content.Mutations.FieldTypeToJsonTypeMapper, Sitecore.Services.GraphQL.Content">
<typeMapping hint="raw:AddTypeMapping">
<map field="treelist" type="Sitecore.Services.GraphQL.Content.Mutations.JsonFields.JsonChecklistField, Sitecore.Services.GraphQL.Content" />
</typeMapping>
</inputTypeMapping>
</fieldTypeMappings>
</content>
</defaults>
</GraphQL>
</api>
</sitecore>
</configuration>
The data need to be sent as an array to add multiple item GUIDs to the field. Your GraphQL query would by similar to this:
mutation UpdateItem {
updateItem(
path: "aaaaaaaa-bbbb-cccc-dddd-5771ad6ed443"
fields: [
{name: "myMultilistFieldName", value: [
"ffffffff-0611-aaaa-8aa9-0b819239a15a",
"eeeeeeee-5fdb-bbbb-a48a-4326b94c7ffa",
"dddddddd-cba4-cccc-a4e9-a3108e538d93",
"cccccccc-e300-dddd-bdd3-6eb182cf8018",
"bbbbbbbb-c2df-eeee-87a5-c90a152f77be",
"aaaaaaaa-c389-ffff-b4b9-62f51f39daa2"
] }
]
)
}
So, when you do your query search, you can see the results list as a string (value) and in an array (targetIds) this way:
Items: items {
Item: item {
id
locationGroup {
value
targetIds
}
}
}
As far as your need to do this for DropLink, you should be able to just add another field mapping to the same patch config file similar to that of the out-of-the-box general link mapping:
<map field="droplink" type="Sitecore.Services.GraphQL.Content.Mutations.JsonFields.JsonGeneralLinkField, Sitecore.Services.GraphQL.Content" />
Hope this helps you out.
| GraphQL Mutation to update DropLink and MultiList field types
From what I'm reading these fields aren't supported?
Create / Update / Delete items in Sitecore via GraphQL
Is there a way to get this to work that someone's found anywhere? We Essentially just want to store GUID or Pipe-seperated GUIDs yeah? Trying to do so doesn't seem to work? Using Sitecore 10.2.
| |
I got to know the reason that templates, where this issue was happening, is due to that I had inherited the /sitecore/templates/Feature/Experience Accelerator/Redirects/Redirect template. As soon as I removed the Redirect template and then again inherited it and then saved then after saving the Layout Details got removed.
When I inherited the page template available at the location /sitecore/templates/Foundation/Experience Accelerator/Multisite/Content/Page then for some reason the layout details removing issue got fixed.
Not sure what is the logic/dependency behind it from Sitecore but this fixed the issue.
So, at the end where this issue was happening with the templates on inheriting the Redirect template, I inherited the page template as well and this fixed the issue for me.
| Template's Standard Values Layout Details removed during deployment
Sitecore 10.2 with SXA
We are facing an unexpected issue when after each deployment a few of the template's Standard Values in Layout Details get removed. As a result this removes all components from all pages based on that template.
For now, we keep the backup of templates and content before deployment, so that when this happens we restore the templates and content back.
But, we checked in our VS solution and found no pipeline that would make this change.
Any recommendations on how to identify the cause of this issue?
| |
According to Sitecore, here is what you will get under this.
Sustaining Support Phase
These are products or product versions that are no longer eligible to be Extended Support products. In rare situations when customers are not able to migrate to the latest product versions before the products are no longer eligible to be Extended Support products, Sitecore provides Sustaining Support as a stop-gap solution for getting limited assistance with production issues and access to online documentation.
For detail information, follow this article.
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0463549
And there are some notes given for all the support states. So according to Sitecore, assistance with product version upgrades is only provided when applying official version upgrade instructions and the Sitecore version being upgraded from is in the Mainstream, Extended, or Sustaining support state, while the version being upgraded to is in the Mainstream support state.
For more details follow this article.
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0641167
| Sitecore Sustaining Support
From 1 Jan 2023 Sitecore 8.2 will be under Sustaining Support
So what does that mean, what is covered by Sitecore, and what limitations/blockers it may bring in this type of support?
What would happen to the website when Sitecore stops supporting this version
| |
By looking at the error it seems that you have an older version of Unicorn in your repository because it is trying to access a method that is not available in later versions, now to fix this you need to remove the older version of Unicorn from your instance.
Now if you see this article, the author is using version 4.1.5, which is compatible with Sitecore 10. Read this article for more details.
https://www.sam-solutions.com/blog/set-up-sitecore-unicorn/
And if you see the latest version in the below article, it is 4.1.7-pre1. So I think you need to try this one. See the nuget version here.
https://www.nuget.org/packages/Unicorn/
Finally, if you will see the Unicorn readme file, it will show some changes in configs that are compatible with Sitecore 10.1 and above. Read this.
https://github.com/SitecoreUnicorn/Unicorn/blob/master/Build/Unicorn.nuget/readme.txt
So you should try the latest release and it will solve your issue.
And one more thing is if you still get some issue after installation then you can join the Sitecore Community Slack and ask in #unicorn. You will get more help from the authors on this.
Hope this helps.
| Method not found: 'System.Web.HttpContext Sitecore.Pipelines.HttpRequest.HttpRequestArgs.get_Context()
During Sitecore upgrade from 9.0 to 10.2, I am getting the following error -
Server Error in '/' Application.
Method not found: 'System.Web.HttpContext Sitecore.Pipelines.HttpRequest.HttpRequestArgs.get_Context()'.
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.MissingMethodException: Method not found: 'System.Web.HttpContext Sitecore.Pipelines.HttpRequest.HttpRequestArgs.get_Context()'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: Method not found: 'System.Web.HttpContext Sitecore.Pipelines.HttpRequest.HttpRequestArgs.get_Context()'.]
Unicorn.ControlPanel.UnicornControlPanelPipelineProcessor.Process(HttpRequestArgs args) +0
(Object , Object ) +14
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +1268
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) +236
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
Sitecore.Web.RequestEventsHandler.OnPostAuthenticateRequest(HttpContextBase context) +218
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +223
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +220
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +94
I tried removing unicorn files and configs as suggested by some forums. but that leads to a "Layout not found error"
Any suggestions on what steps need to be taken? What version should I use for Unicorn?
Any help would be appreciated.
| |
There were some duplicate items in our Sitecore content tree(Master DB) inside experience analytics folder. We have cleaned up and it is working fine now.
| Experience analytics graph is not loading in Sitecore 10.2
We were working on Sitecore 10.2 upgrade.
We are not able to see the experience graph, but we can see the graph in our lower environment(UAT) with same database.
Can you help us to find the troubleshooting steps?
| |
Here is something about the events and remote events in Sitecore.
What is an Event?
Events in Sitecore are similar to events in other systems: something triggers an event and there are handlers that are configured to handle the event.
Event handlers are similar to pipelines in how they are configured. An event handler is a .NET class that implements a method. When an event is triggered, the event handlers are run in order.
Event handlers are defined in Sitecore patch files.
The following is an example of the event handler that handles the item:deleted event.
<event name="item:deleted">
<handler type="Sitecore.Links.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeleted" />
<handler type="Sitecore.Tasks.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeleted" />
<handler type="Sitecore.Globalization.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeleted" />
<handler type="Sitecore.Data.Fields.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeleted" />
<handler type="Sitecore.Rules.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeleted" />
</event>
What is a Remote Event?
When an event is triggered, the event handlers on that server run. For example, when an item is saved, the item:saved event is fired on that server. That causes the database to be updated and for the cache to be updated.
But what happens if you are using a multi-server environment? The database has already been updated, so that doesn’t need to happen again. But the item may be cached on the other servers, so the cache needs to be updated. This is what remote events do. They ensure the appropriate handlers are run on remote servers.
The following is an example of the remote event handler for the item:deleted event. Another way of describing the following is it is an example of the event handlers for the remote:item:deleted event.
<event name="item:deleted:remote">
<handler type="Sitecore.Globalization.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeletedRemote" />
<handler type="Sitecore.Data.Fields.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeletedRemote" />
<handler type="Sitecore.Rules.ItemEventHandler, Sitecore.Kernel"
method="OnItemDeletedRemote" />
</event>
If your event requires a remote event be triggered on remote servers, you need to be sure that you raise the remote event.
In a multi-server Sitecore environment, the term “remote” describes each of the other servers in the environment. It is a relative designation. Remote servers are all of the servers in the environment except for the server that the code is currently running on.
And here are some code snippets that you can use for this:
https://sitecore-community.github.io/docs/pipelines-and-events/events/#event_basics
| Remote Event in Sitecore
what is the difference between normal event and remote events ? And when to customize the remote one ? Can someone please help me understand this with a practical scenario ?
for e.g.
name="item:created"
name="item:created:remote"
name="item:cloneAdded"
name="item:cloneAdded:remote"
| |
In xyz-app.config add the following to the app registration section (doesn't matter where in the list of values):
<app name="xyz-app"...
...
serverSideRenderingEngineEditOnly="false" />
Default value for this is true, which seems to disable the rendering engine from loading outside Experience Editor.
In our environment we had the same issue as OP, setting the value in the app registration section of the config allowed the page to load again as expected - Worth noting though that it's still offloading the rendering to the rendering host, so it's just extra hops compared to going to the rendering host URL directly.
| Sitecore JSS URL redirecting to not found
Getting the below error when browsing the app URL in connected mode:
On browsing https://xyz-app.dev.local it gets redirected to https://xyz-app.dev.local/sitecore/service/notfound.aspx
I can see the JSON response for it on https://xyz-app.dev.local/sitecore/api/layout/render/jss?item=/&sc_apikey={ABC}&sc_site=xyz-app
I can also see the content on http://localhost:3000/ and experience editor.
Sitecore version - 10.3
JSS version - 21.0.2
Framework - NextJs
xyz-app.config:
<sites>
<site patch:before="site[@name='website']"
inherits="website"
name="xyz-app"
hostName="xyz-app.dev.local"
rootPath="/sitecore/content/xyz-app"
startItem="/home"
database="master" />
</sites>
<app name="xyz-app"
layoutServiceConfiguration="default"
sitecorePath="/sitecore/content/xyz-app"
useLanguageSpecificLayout="true"
graphQLEndpoint="/sitecore/api/graph/edge"
inherits="defaults"
serverSideRenderingEngine="http"
serverSideRenderingEngineEndpointUrl="http://localhost:3000/api/editing/render"
serverSideRenderingEngineApplicationUrl="http://localhost:3000" />
</apps>
scjssconfig.json:
{
"sitecore": {
"instancePath": "C:\\inetpub\\wwwroot\\sitecore103.dev.local",
"apiKey": "ABC",
"deploySecret": "abc",
"deployUrl": "https://xyz-app.dev.local/sitecore/api/jss/import",
"layoutServiceHost": "https://xyz-app.dev.local"
}
}
I've allowed all (*) for CORS origin and allowed controls on the API key.
| |
Create a new processor to validate a single session on <owin.cookieAuthentication.signedIn> pipeline, if the same username is already logged in on other devices, we kick out the session and then remove the user's ticket from Sitecore TicketManager.
App_Config\Sitecore\Owin.Authentication\Sitecore.Owin.Authentication.config
<configuration>
<sitecore>
<pipelines>
<owin.cookieAuthentication.signIn>
<processor resolve="true" type="your.SIGN-IN.pipeline, YourDLL" patch:after="processor[@type='Sitecore.Owin.Authentication.Pipelines.CookieAuthentication.SignIn.RemoveTicket, Sitecore.Owin.Authentication']" />
</owin.cookieAuthentication.signIn>
</pipelines>
</sitecore>
</configuration>
Create ValidateSingleSession class inherit from SignedInProcessor
using System;
using Sitecore.Abstractions;
using Sitecore.Owin.Authentication.Pipelines.CookieAuthentication.SignedIn;
using Sitecore.Web.Authentication;
using System.Collections.Generic;
namespace Sitecore.SitecoreExtensions.Owin.Authentication.Pipelines
{
public class ValidateSingleSession : SignedInProcessor
{
protected BaseTicketManager TicketManager { get; }
public ValidateSingleSession(BaseTicketManager ticketManager)
{
this.TicketManager = ticketManager;
}
public override void Process(SignedInArgs args)
{
if (!string.Equals(args.Site.Name, "shell", StringComparison.Ordinal))
return;
var validateSingleSession = Sitecore.Configuration.Settings.GetSetting("Security.ValidateSingleSession");
if (!bool.Parse(validateSingleSession))
return;
List<DomainAccessGuard.Session> userSessionList = DomainAccessGuard.Sessions;
if (userSessionList != null && userSessionList.Count > 0)
{
foreach (DomainAccessGuard.Session userSession in userSessionList.ToArray())
{
if (args.User.UserName == userSession.UserName)
{
DomainAccessGuard.Kick(userSession.SessionID);
Sitecore.Diagnostics.Log.Audit($"Concurrent sessions detected: User {userSession.UserName} is kicked out ", this);
}
}
}
//remove ticket
var ticketIds = this.TicketManager.GetTicketIDs();
if (ticketIds != null && ticketIds.Count > 0)
{
foreach (var ticketID in ticketIds)
{
var ticket = this.TicketManager.GetTicket(ticketID);
if (args.User.UserName == ticket.UserName)
{
this.TicketManager.RemoveTicket(ticketID);
}
}
}
}
}
}
Also created a field to allow the development team to disable single-session validation by introducing Security.ValidateSingleSession setting in config.
For more detailes visit the link - https://edwenkerk.hashnode.dev/sitecore-10-single-login-session-and-kick-idle-user
| How to prevent multiple sessions from same user
We are using Sitecore 10.1.2
The CMS uses both native & Azure AD logins.
A user is able to login to the CMS in multiple simultaneous sessions/browsers/from different IPs.
Is it possible to prevent this by any config setting. If it is a custom implementation, please provide any pointers on where and how to achieve this.
| |
There are two options available to you.
The first and the recommended approach is to do as you have done and downgrade the reference in your visual studio solution to match what is running in the sitecore instance. This will ensure that the sitecore DLLs are running against what was intended and fully tested.
The second approach would be to add a binding redirect to the Web config file. This would look similar to the below:
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="5.2.4.0-5.2.9.0" newVersion="5.2.4.0" />
</dependentAssembly>
This will ensure any previous references, baked into your custom DLL will be redirected to the version that exists in the bin folder.
| System.web.Mvc version conflict in instance & code
I have a fresh instance with v10.1.2, which has System.Web.Mvc 5.2.4
In my Visual Studio solution, I have projects with .Net 4.8 which has System.Web.Mvc 5.2.9.
When I publish the code into the instance, it is only the custom dlls and pdb files. They do not include System.Web.Mvc.
But still, the CMS doesn't load and throws an error saying, cannot find the System.Web.Mvc version.
To handle this, I have downgraded Microsoft.AspNet.Mvc to 5.2.4.
The issue is now resolved.
But for each project and all the new projects, this step needs to be done.
If I include System.Web.Mvc (5.2.9) in publish, then the web.config of the instance for all environments (DEV,UAT, PRD) have to be updated.
What is the better way to handle this?
| |
It logged something as Sitecore.CES.GeoIp that leads me towards an investigation for Sitecore device detection and GeoIP lookup.
As Device Detection module is enabled by default and requires access to Sitecore services to download and update the device database. more details here (https://doc.sitecore.com/xp/en/developers/103/sitecore-experience-manager/configure-sitecore-device-detection.html)
The Device Detection module is enabled by default. However, if you want to prevent the Device Detection client from contacting the Device Detection service every day (which is the default setting), and you do not need the Device Detection functionality, then you can disable the module.
To resolve this, I disabled the device detection and GeoIP lookup setting with the below patch:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore role:require="Standalone or ContentManagement or ContentDelivery">
<settings>
<setting name="DeviceDetection.Enabled">
<patch:attribute name="value" value="false" />
</setting>
<setting name="GeoIp.PerformLookup">
<patch:attribute name="value" value="false" />
</setting>
</settings>
</sitecore>
</configuration>
Hope it helps!
| GraphQL queries take time to execute and failed with Errors
Sitecore instance running on Sitecore 10.3, JSS, nextjs with Graphql locally, I did enable graphql master endpoint to execute graphql queries.
It was taking such a long time to execute simple queries with GraphiQL GUI.
Query code:
query GetChildren($itemId: String!){
item(path:$itemId){
name
hasChildren
children{
name
id
}
}
}
Noticed the following errors in the log file.
Exception: System.Web.HttpException
Message: The request queue limit of the session is exceeded.
Source: System.Web
at System.Web.SessionState.SessionStateModule.QueueRef()
at System.Web.SessionState.SessionStateModule.PollLockedSession()
at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Exception: Polly.CircuitBreaker.BrokenCircuitException
Message: The circuit is now open and is not allowing calls.
Source: Polly
at Polly.CircuitBreaker.CircuitStateController`1.OnActionPreExecute()
at Polly.CircuitBreaker.CircuitBreakerEngine.<ImplementationAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsyncInternal>d__181`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsync>d__121`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Wrap.PolicyWrapEngine.<>c__DisplayClass8_0`1.<<ImplementationAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<>c__DisplayClass181_0`1.<<ExecuteAsyncInternal>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.RetrySyntaxAsync.<>c__DisplayClass25_1.<<WaitAndRetryAsync>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Polly.Retry.RetryEngine.<ImplementationAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Polly.Retry.RetryEngine.<ImplementationAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsyncInternal>d__181`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsync>d__121`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Wrap.PolicyWrapEngine.<ImplementationAsync>d__8`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsync>d__121`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAndCaptureAsync>d__139`1.MoveNext()
Nested Exception
Exception: System.Net.WebException
Message: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Source: System
at System.Net.HttpWebRequest.GetResponse()
at Sitecore.CES.Client.WebClient.<>c__DisplayClass6_0.<ExecuteRequest>b__0()
at Sitecore.CES.Client.WebClient.Execute[T](Func`1 action, String requestUri)
at Sitecore.CES.Client.ResourceConnector`1.Request(String endpoint, Object[] parameters)
at Sitecore.CES.Discovery.EndpointSource.GetEndpoint(String serviceName)
at Sitecore.CES.GeoIp.SitecoreProvider.RequestGeoIpService(String ip)
at Sitecore.CES.GeoIp.SitecoreProvider.GetWhoIsInformationByIp(String ip)
at Sitecore.CES.GeoIp.Core.Fetcher.Providers.LookupGeoIpFetcher.CallLookupService(GeoIpRequest geoIpRequest)
at Sitecore.CES.GeoIp.Core.Fetcher.Providers.LookupGeoIpFetcher.FetchAsync(GeoIpRequest geoIpRequest)
at Sitecore.CES.GeoIp.Core.Fetcher.GeoIpFetcher.<>c__DisplayClass10_0.<<DoFetchFromLookup>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<>c__DisplayClass181_0`1.<<ExecuteAsyncInternal>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.CircuitBreakerSyntaxAsync.<>c__DisplayClass5_1.<<CircuitBreakerAsync>b__2>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.CircuitBreaker.CircuitBreakerEngine.<ImplementationAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsyncInternal>d__181`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<ExecuteAsync>d__121`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Wrap.PolicyWrapEngine.<>c__DisplayClass8_0`1.<<ImplementationAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.Policy.<>c__DisplayClass181_0`1.<<ExecuteAsyncInternal>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Polly.RetrySyntaxAsync.<>c__DisplayClass25_1.<<WaitAndRetryAsync>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Polly.Retry.RetryEngine.<ImplementationAsync>d__1`1.MoveNext()
Any thoughts?
Thank you in advance.
| |
A few observations I've made while working over VPN (in particular Palo Global Protect):
Container networking appears to get disrupted when the VPN disconnects. Tearing down the containers with docker compose down and then docker compose up -d appears to correct the issue. I think this is because a new network is created which doesn't conflict with the VPN.
The running containers use the new network which may be why containers can reach the internet.
Building containers use the default network. Creating a new network and associating it with the build would create a similar scenario as the running containers.
Start by creating a new build.ps1:
param(
[string[]]$Services
)
$networkResult = docker network inspect build-nat | ConvertFrom-Json
if(!$networkResult) {
docker network create --driver nat build-nat
}
docker compose -f .\docker-compose.build.yml build $Services
docker network rm build-nat
Add the network to your build section in docker-compose.yml:
node:
image: ${REGISTRY}${COMPOSE_PROJECT_NAME}-node:${VERSION}
build:
context: ./docker/build/node
network: build-nat
args:
BASE_IMAGE: ${NODE_BASE_IMAGE}
NODE_VERSION: ${NODE_VERSION}
| How to build custom docker images with a specific network?
While building custom images (like extending the cm) I've seen various networking issues when on VPN. I noticed that containers can reach the internet with docker compose up but the same resources can't be reached during build.
Is there way way to specify a custom network when building images in docker-compose.yml?
| |
We literally had the same problem with SC10.3, SXA and JSS 21.0. The issue was due two things:
In .\src\lib\layout-service-factory.ts change the configurationName property from default to sxa-jss. Probably JSS should handle the default value based on the site configuration, but it did not work for us.
When I did that, the LayoutService started throwing 500s due to not having the master DB configured (the JSS app was connecting to the CD server). The issue was in this config App_Config\Modules\JSS SXA\Foundation\Sitecore.XA.JSS.Foundation.Presentation.config, namely, in having no transform for the CD server here:
<config name="sxa-jss">
<requestContext type="Sitecore.LayoutService.Configuration.DefaultRequestContext, Sitecore.LayoutService">
<databaseName>master</databaseName> <-- HERE
</requestContext>
We ended up creating a config override like this:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<layoutService>
<configurations>
<config name="sxa-jss">
<requestContext type="Sitecore.LayoutService.Configuration.DefaultRequestContext, Sitecore.LayoutService">
<databaseName role:require="ContentDelivery">
<patch:delete />
</databaseName>
<databaseName role:require="ContentDelivery">web</databaseName>
</requestContext>
</config>
</configurations>
</layoutService>
</sitecore>
</configuration>
| SXA headless with (partial) design: placeholder not found
I am using Sitecore 10.3 with SXA and JSS. For the head setup I used a post from Dan Cruickshank and that worked fine. I did get a nice blank homepage and no errors.
I created 3 partial designs and added those to a design which I linked to the default page template. So far still fine. But as soon as I add components to any of the partial designs it goes wrong. It seems to be a mismatch in placeholder naming, but not sure how to fix it - especially since this is still all out-of-the-box SXA and the starter template.
The error in the logs are "placeholder 'sxa-header' was not found in the current rendering data" (I named the partial "header"). It's a very typical error in JSS setups but I don't know how and where to fix this in SXA 10.3.
What I noticed:
when I create a partial design "header", a placeholder setting item is created with the same name and a placeholder key "sxa-header".
when I add components in this partial design, those components are added in the placeholders that are defined in the layout file which are called like "headless-header"
The rendered layout as seen in the graphql ui looks like:
"headless-header": [
{
"uid": "36add71b-256e-4af8-9a76-6b764e0013d4",
"componentName": "PartialDesignDynamicPlaceholder",
"dataSource": "",
"params": {
"sid": "{5C0F944B-5573-471D-824B-9BF6AF058FB0}",
"ph": "headless-header",
"sig": "sxa-header"
}
}
],
So I have a ph which is consistent with the placeholder and a sig which refers to the placeholder key in the local (site) placeholder settings item.
I tried several things (things that I should not be doing in a standard SXA setup but just to debug and understand the issue) but nothing worked so far.
The error comes from the PartialDesignDynamicPlaceholder component. This uses indeed the sig parameter: <Placeholder name={props.rendering?.params?.sig || ''} rendering={props.rendering} />.
I assume I am just missing something silly, but I'm not sure what and can't find something in the documentation. Any ideas?
Small update: I managed to get rid of the errors by adding the placeholders to the "Layout Service Placeholders" field of the "PartialDesign Dynamic Placeholder" rendering. Which is something I should not be doing manually (especially as I need to use raw values tricks to add them). But I still get an empty page so now I have no errors and no data :(
| |
I have tried replicating your setup on an empty Sitecore installation and can confirm that the custom regex validation rule works in exactly the same way as standard Sitecore regex rules.
For example, I applied the rule with regex pattern ^\S.*\S$ to the Sample Item template and it shows validation messages in Content Editor correctly:
However, this configuration does not prevent items from being saved and may be too subtle for content editors to notice.
If this rule is critical and you want to stop users from saving items with this validation error, just add the parameter &Result=FatalError to the Parameters field on the validation rule item like this:
Once this is added, Sitecore will not save incorrect field values and instead will throw an error message saying that fatal validation errors must be resolved before the item can be saved:
| Regex field validator does not work in Sitecore
I created a validation rule that should use regular expressions for checking if a field contains leading and trailing spaces. If it contains a space at the start or end of the field value, I expect it to throw an error on item save.
This is the regex pattern I created: ^\S.*\S$
The steps I took for creating the validation rule are as follows:
I created a validation rule item and called it "Trim Title", it's full path is /sitecore/system/Settings/Validation Rules/Field Rules/foldereName/Trim Title
In the Type field I referenced
Sitecore.Data.Validators.FieldValidators.RegexValidator, Sitecore.Kernel
In the Parameters field I specified
Pattern=^\S.*\S$&Text=Field "{0}" You cannot have a leading or trailing whitespace.
This is how my validation rule item looks in Content Editor:
Then I went to my template "Headline Field" and under the Validation Rules section I selected my Trim Title validation rule in the fields Quick Action Bar, Validation Button, and Validation Bar.
I tried to test the field validation and it always fails. For example, if I enter some text with trailing and leading spaces it still saves the item and does not throw a validation error.
My idea was to create a regex rule similar to the Sitecore standard rule "Is Email". I replicated the same setup and simply changed the regex pattern but my rule does not work. What can be wrong with my validation rule?
| |
To remove/customize it from the Richtext editor, I would recommend creating a custom rich text editor to customize as per your need and as a best practice to reduce complexity and challenges during a future upgrade.
To do this you need to switch to the Core Database – at the bottom right in the Desktop view is a little grey icon: click that and choose Core from the popup.
Goto this path and find predefined editor profiles /sitecore/system/Settings/Html Editor Profiles
For you its (Rich Text Default) /sitecore/system/Settings/Html Editor Profiles/Rich Text Default
Right-click the folder and select the duplicate option from the context menu. Provide meaning full name like Custom Rich Text Default and hit Ok.
Expand Toolbar 1 item (/sitecore/system/Settings/Html Editor Profiles/Custom Rich Text Default/Toolbar 1) and delete (/sitecore/system/Settings/Html Editor Profiles/Custom Rich Text Default/Toolbar 1/Insert Sitecore Media) item.
Save and switch to master dataset and change the source filed path for the template you want to use newly created custom richtext editor (/sitecore/system/Settings/Html Editor Profiles/Custom Rich Text Default)
Validate with Richtext editor.
Hope it helps!
| Disable Image Upload button in Rich Text Editor
Is it possible to remove/disable the image icon in the Rich Text Editor's toolbar.
All the images in this project come from Content Hub and client wants the CMS feature for image uploads to be disabled.
| |
Hope this will help for you
please install Sitecore Docker Tools Manually using below commands
Install-Package SitecoreDockerTools -Version 10.1.4 -Source sitecore.myget.org/F/sc-powershell/api/v3/index.json
| The term 'Write-SitecoreDockerWelcome' is not recognized as the name of a cmdlet, function
We're trying to init docker on a new dev machine however we're running into issues... it appears that sitecore docker tools is not installing?
The error is
Installing SitecoreDockerTools...
Importing SitecoreDockerTools...
C:\sitecore\init.ps1 : The term 'Write-SitecoreDockerWelcome' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
At line:1 char:1
+ .\init.ps1 -LicenseXmlPath "C:\license\license.xml"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Write-SitecoreDockerWelcome:String) [init.ps1], CommandNotFoundExceptio
n
+ FullyQualifiedErrorId : CommandNotFoundException,init.ps1
The script is:
Check for Sitecore Gallery
Import-Module PowerShellGet
$SitecoreGallery = Get-PSRepository | Where-Object { $_.SourceLocation -eq "https://sitecore.myget.org/F/sc-powershell/api/v2" }
if (-not $SitecoreGallery) {
Write-Host "Adding Sitecore PowerShell Gallery..." -ForegroundColor Green
Register-PSRepository -Name SitecoreGallery -SourceLocation https://sitecore.myget.org/F/sc-powershell/api/v2 -InstallationPolicy Trusted
$SitecoreGallery = Get-PSRepository -Name SitecoreGallery
}
# Install and Import SitecoreDockerTools
$dockerToolsVersion = "10.0.5"
Remove-Module SitecoreDockerTools -ErrorAction SilentlyContinue
if (-not (Get-InstalledModule -Name SitecoreDockerTools -RequiredVersion $dockerToolsVersion -ErrorAction SilentlyContinue)) {
Write-Host "Installing SitecoreDockerTools..." -ForegroundColor Green
Install-Module SitecoreDockerTools -RequiredVersion $dockerToolsVersion -Scope CurrentUser -Repository $SitecoreGallery.Name -AllowClobber
}
Write-Host "Importing SitecoreDockerTools..." -ForegroundColor Green
Import-Module SitecoreDockerTools -RequiredVersion $dockerToolsVersion
Write-SitecoreDockerWelcome <--- Fails here
Running each line manually shows no errors, calling Get-PSRepository shows SitecoreGallery as a trusted source.
Running Get-InstalledModule also shows a single SitecoreDockerTools under the correct version (This is expected as it's a fresh windows machine).
So everything appears to be installed but the commands are just not found.
Any advice appreciated!
Edit
On inspection of our repo, it looks like a commit of our init.ps1 file was downgraded to 10.0.5 from 10.1.4 for the SitecoreDockerTools module
| |
This problem is the same as any other model based parameter binding scenario whereby one of your params/properties is a list of some simple type (e.g. List<Guid>). The Sitecore ID class does seem to be treated as a "simple" type, similar to the Guid type in terms of param binding. This makes sense because an ID IS a Guid. This is an important point, because it shows that the ID class is not seen as a complex / custom type by the runtime (which would require custom binding logic).
As the comments mentioned:
Formatting the query string as ?TemplateIds ={guid}&TemplateIds ={guid} does work. This is the standard approach when using model binding for list fields. One obvious drawback is that the query string may be longer and more verbose than you would like.
Parameter binding also works, although there are simpler options such as...
A manual approach:
[HttpGet]
[Route("sitecore/api/search")]
public IHttpActionResult Search(string? templateIds = null)
{
var filter = new MySearchFilter
{
TemplateIds = types.ToIds()
};
}
Where ToIds() is something like:
public static List<ID> ToIds(this string? value)
{
if (value != null)
{
string[] ids = value.Split(',', '|');
return ids
.Select(x => ID.TryParse(x, out ID id) ? id : ID.Null)
.Where(x => !ID.IsNullOrEmpty(x))
.ToList();
}
return new List<ID>();
}
This way the query string can be formatted as a comma separated string:
?TemplateIds={xxxx},{xxxx}
The benefit of the manual approach is having more control over which params can be accessed if the param model contains many fields, some of which may not be relevant or may be lacking an implementation. The manual approach is simple, flexible, and potentially more secure, but it can result in a good amount of code duplication if this pattern is implemented in many different areas.
| ICollection<ID> property not populating correctly in API controller method when using FromUri + Model
I have an API route that uses [FromUri] in combination with a custom class that defines the values that can be passed in via query string params:
[HttpGet]
[Route("sitecore/api/search")]
public IHttpActionResult Search([FromUri] MySearchFilter filter)
{
...
}
public class MySearchFilter
{
public ICollection<ID>? TemplateIds { get; set; }
}
However, whenever I ping /sitecore/api/search?templateIds={xxxx-xxxx}, the TemplateIds value never contains the ID that was specified in the query string, and the value changes every time.
I also tried using short IDs and changing the property type to List<ID> and IEnumerable<ID>. The issue only seems to resolve when I change the property type to IEnumerable<System.Guid>.
Is this an issue with the Sitcore.Data.ID class?
Using Sitecore 10.1.
| |
I solved this issue by adding CookieManager property like below code:
public OpenIdConnectAuthenticationOptions SetupOidcOptions(
string authenticationType,
bool saveSigninToken)
{
var oidcOptions = new OpenIdConnectAuthenticationOptions
{
AuthenticationType = authenticationType,
Authority = authority,
ClientId = clientId,
ClientSecret = clientSecret,
ResponseType = OpenIdConnectResponseType.IdTokenToken,
RedirectUri = redirectUri,
PostLogoutRedirectUri = postLogoutRedirectUri,
Scope = OpenIdConnectScope.OpenIdProfile + " " + OpenIdConnectScope.OfflineAccess,
SaveTokens = true,
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = this.RedirectToIdentityProviderAsync,
SecurityTokenValidated = this.SecurityTokenValidatedAsync,
AuthenticationFailed = (context) =>
{
if (context.Exception.Message.Contains(errorCode))
{
context.HandleResponse();
context.OwinContext.Authentication.Challenge();
}
return Task.FromResult(true);
}
},
TokenValidationParameters =
{
SaveSigninToken = saveSigninToken
},
CookieManager = cookieManager
};
return oidcOptions;
}
| Custom identity provider issue on Chrome
I had done SSO authentication which is working locally and on-premise, when I deployed on AWS, it was not working on Chrome but working on Mozilla.
public class ProjectIdentityProvider : IdentityProvidersProcessor
{
private readonly ICookieManager cookieManager;
public ProjectIdentityProvider(
FederatedAuthenticationConfiguration federatedAuthenticationConfiguration,
ICookieManager cookieManager,
BaseSettings settings) : base(federatedAuthenticationConfiguration, cookieManager, settings)
{
this.cookieManager = cookieManager ?? throw new ArgumentNullException(nameof(cookieManager));
}
protected override void ProcessCore(IdentityProvidersArgs args)
{
var authenticationType = this.GetAuthenticationType();
var identityProvider = this.GetIdentityProvider();
var saveSigninToken = identityProvider.TriggerExternalSignOut;
var oidcOptions = this.SetupOidcOptions(authenticationType, saveSigninToken);
args.App.UseOpenIdConnectAuthentication(oidcOptions);
}
public OpenIdConnectAuthenticationOptions SetupOidcOptions(
string authenticationType,
bool saveSigninToken)
{
var oidcOptions = new OpenIdConnectAuthenticationOptions
{
AuthenticationType = authenticationType,
Authority = authority,
ClientId = clientId,
ClientSecret = clientSecret,
ResponseType = OpenIdConnectResponseType.IdTokenToken,
RedirectUri = redirectUri,
PostLogoutRedirectUri = postLogoutRedirectUri,
Scope = OpenIdConnectScope.OpenIdProfile + " " + OpenIdConnectScope.OfflineAccess,
SaveTokens = true,
Notifications = new OpenIdConnectAuthenticationNotifications
{
RedirectToIdentityProvider = this.RedirectToIdentityProviderAsync,
SecurityTokenValidated = this.SecurityTokenValidatedAsync,
AuthenticationFailed = (context) =>
{
if (context.Exception.Message.Contains(errorCode))
{
context.SkipToNextMiddleware();
}
return Task.FromResult(true);
}
},
TokenValidationParameters =
{
SaveSigninToken = saveSigninToken
},
};
return oidcOptions;
}
protected override string IdentityProviderName => "ProjectIdentityProvider";
protected BaseLog Log { get; }
public Collection<string> Scopes { get; } = new Collection<string>();
private Task RedirectToIdentityProviderAsync(
RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>
notification)
{
var owinContext = notification.OwinContext;
var protocolMessage = notification.ProtocolMessage;
var user = Sitecore.Context.User;
if (protocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
{
protocolMessage.RedirectUri = postLogoutRedirectUri;
}
if (protocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
protocolMessage.PostLogoutRedirectUri = postLogoutRedirectUri;
protocolMessage.IdTokenHint = this.GetIdTokenHint(owinContext);
}
return Task.CompletedTask;
}
private Task SecurityTokenValidatedAsync(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
var identityProvider = this.GetIdentityProvider();
var identity = notification.AuthenticationTicket.Identity;
foreach (var current in identityProvider.Transformations)
{
current.Transform(identity, new TransformationContext(this.FederatedAuthenticationConfiguration, identityProvider));
}
return Task.CompletedTask;
}
}
| |
I was able to reproduce both errors as you mentioned with my local environment using Sitecore Azure Toolkit 2.7.0.
As part of Prerequisites while using Sitecore Azure Toolkit, It require to install Data-Tier Application Framework (https://doc.sitecore.com/xp/en/developers/sat/27/sitecore-azure-toolkit/getting-started-with-the-sitecore-azure-toolkit.html)
It gets resolved by following steps:
I installed Microsoft SQL Server Data-Tier Application Framework (DacFX) for SQL server 2012 or later.
Restart the system after installation.
Any of this command works perfectly fine.
ConvertTo-SCModuleWebDeployPackage -Path $package -Destination $destination -DisableDacPacOptions * -Force
ConvertTo-SCModuleWebDeployPackage -Path $package -Destination $destination -Force
Hope it helps!
| Error related to scriptDatabaseOptions when generating scwdp using Azure Toolkit
Sitecore Azure Toolkit 2.7.0 and 2.8.0
Trying to convert a module package into an scwdp package using the following command:
$package = "C:\temp\MyModulePackage.zip"
ConvertTo-SCModuleWebDeployPackage -Path $package -Destination $destination -DisableDacPacOptions * -Force
Provider 'dbDacFx' does not support setting 'scriptDatabaseOptions'.
If I remove the parameter DisableDacPacOptions then it complains:
ConvertTo-SCModuleWebDeployPackage : The SQL provider cannot run with dacpac option because of a missing dependency.
Please make sure that DacFx is installed. Learn more at:
https://go.microsoft.com/fwlink/?LinkId=221672#ERROR_DACFX_NEEDED_FOR_SQL_PROVIDER.
What could be the possible cause for the scriptDatabaseOptions error?
| |
Calling my class like this, worked for me
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<owin.cookieAuthentication.signedIn>
<processor patch:before="*[@type='Sitecore.Owin.Authentication.Pipelines.CookieAuthentication.SignedIn.CreateTicket, Sitecore.Owin.Authentication']"
type="MyProject.Foundation.Accounts.CMS.CmsLoginAudit.SaveAuditLog, MyProject.Foundation.Accounts" resolve="true"/>
</owin.cookieAuthentication.signedIn>
</pipelines>
</sitecore>
</configuration>
| How to extend the existing login process
Using Sitecore 10.1.2
I would like to log the CMS user information like username, email, and logged-in timestamp as soon as a user logs into the CMS.
The details would be captured in a custom table with some business logic.
We have both native CMS & Azure AD accounts.
Could you please suggest the method, processor or pipeline where I can add my custom logic?
Update:
Following the suggestion, I have implemented this.
These are the existing settings from ShowConfig.aspx.
My patch config:
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<processors>
<loggedin argsType="Sitecore.Pipelines.LoggedIn.LoggedInArgs">
<processor mode="on" type="MyProject.Foundation.Accounts.CMS.CmsLoginAudit.SaveAuditLog, MyProject.Foundation.Accounts" resolve="true"/>
</loggedin>
</processors>
</pipelines>
</sitecore>
</configuration>
And the class:
namespace MyProject.Foundation.Accounts.CMS
{
public class CmsLoginAudit
{
public void SaveAuditLog()
{
if (Context.IsLoggedIn)
{
User user = Context.User;
MembershipUser membershipUser = Membership.GetUser(user.Name);
var userId = membershipUser?.ProviderUserKey;
var userIp = GetUserIpAddress();
string userEmail = membershipUser.Email;
}
}
}
}
The ShowConfig.aspx does include the the patch config settings.
But the debugger isn't hitting the SaveAuditLog method.
What am I missing here.
| |
Managed Schema
This is needed after adding a new index/core or when new field types are configured in the Sitecore config. Many of the fields are dynamic so you may rarely run this.
I added Managed Synonyms to the text field which required the schema to be repopulated; this is because all of the schema data needs to be resent to Solr.
As you can see below, the schema for the sxacontent field is dynamic ergo the _*txm in the name.
Expect to run this for new installations, crawling config changes, or when the current schema is missing something.
Indexing Manager
This is needed any time templates are added/modified. Imagine you have documents with Title and Text. If you add a new template field for Metatitle then none of the existing documents will have this new field
Only rebuild indexes that need it. I like to have a custom index per site or line of business; this allows me to restrict the crawling to specific parts of the tree. The OOTB indexes like sitecore_web_index are rooted at /sitecore which means it could take far more time than necessary.
Example: The following demonstrates how to reduce the scope of the crawlers (and remove the original). In my case I don't actually use sitecore_web_index and sitecore_sxa_web_index because there are custom indexes for each line of business.
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore role:require="Standalone or ContentManagement or ContentDelivery">
<contentSearch>
<configuration>
<indexes>
<index id="sitecore_web_index">
<locations>
<patch:delete />
</locations>
<locations hint="list:AddCrawler">
<crawler name="templates" type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>web</Database>
<Root>/sitecore/templates</Root>
</crawler>
<crawler name="content" type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>web</Database>
<Root>/sitecore/content/home</Root>
</crawler>
</locations>
</index>
<index id="sitecore_sxa_web_index">
<locations>
<patch:delete />
</locations>
<locations hint="list:AddCrawler">
<crawler name="templates" type="Sitecore.XA.Foundation.Search.Crawlers.SxaItemCrawler, Sitecore.XA.Foundation.Search">
<Database>web</Database>
<Root>/sitecore/templates</Root>
</crawler>
<crawler name="content" type="Sitecore.XA.Foundation.Search.Crawlers.SxaItemCrawler, Sitecore.XA.Foundation.Search">
<Database>web</Database>
<Root>/sitecore/content/home</Root>
</crawler>
</locations>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
</configuration>
If you use SwitchOnRebuild you could end up rebuilding twice to ensure consistency between the two Solr cores.
Based on your indexing strategy you may see the rebuild happen automatically following large volumes of content changes.
Expect to run this following deployments which include template or search config changes. A change in the list of crawlers could result in a reduction/increase in records. I managed to shave 250 MB from a Solr core by eliminating unnecessary documents.
| What is the difference between Populate Solr Managed Schema & Indexing Manager features
Please help me understand these features.
What is the difference between these two features in the control panel - Populate Solr Managed Schema & Indexing Manager?
When to use which?
How often should I rebuild the index. Is it after every template/rendering/content creation.
I have created some content items under /sitecore/content. These are from different templates.
In the Solr portal, only few of them show up and the rest don't. I have rebuilt the indexes for both the features.
| |
This is how I did it.
I created a custom content resolver, and it looks like this:
using Newtonsoft.Json.Linq;
using Sitecore.Diagnostics;
using Sitecore.LayoutService.Configuration;
using Sitecore.LayoutService.ItemRendering.ContentsResolvers;
using Sitecore.Mvc.Presentation;
using SitecoreSandbox.Extensions;
namespace SitecoreSandbox.Resolvers
{
public class GenericResolver : RenderingContentsResolver
{
protected Rendering _rendering;
protected IRenderingConfiguration _renderingConfig;
public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
{
Assert.ArgumentNotNull(rendering, "rendering");
Assert.ArgumentNotNull(renderingConfig, "renderingConfig");
_rendering = rendering;
_renderingConfig = renderingConfig;
var item = GetContextItem(_rendering, _renderingConfig);
var jObject = JObject.Parse(_renderingConfig.ItemSerializer.Serialize(item));
return jObject.ToCamelCase();
}
}
}
It uses a custom extension ToCamelCase():
using System.Diagnostics.Contracts;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace SitecoreSandbox.Extensions
{
public static class JTokenExtensions
{
[Pure]
public static JObject ToCamelCase(this JObject original)
{
var newObj = new JObject();
foreach (var property in original.Properties())
{
var newPropertyName = property.Name.Replace(" ", string.Empty).ToCamelCaseString();
newObj[newPropertyName] = property.Value.ToCamelCaseJToken();
}
return newObj;
}
// Recursively converts a JToken with PascalCase names to camelCase
[Pure]
public static JToken ToCamelCaseJToken(this JToken original)
{
switch (original.Type)
{
case JTokenType.Object:
return ((JObject)original).ToCamelCase();
case JTokenType.Array:
return new JArray(((JArray)original).Select(x => x.ToCamelCaseJToken()));
default:
return original.DeepClone();
}
}
// Convert a string to camelCase
[Pure]
public static string ToCamelCaseString(this string str)
{
if (!string.IsNullOrEmpty(str))
{
return char.ToLowerInvariant(str[0]) + str.Substring(1);
}
return str;
}
}
}
Then I configured my rendering to use this custom content resolver:
This is what a configuration for a content resolver looks like. Please note that you need to create a similar content resolver for items with child items.
And this is what my ContetBlock template looks like:
And as a bonus, everything is working as expected in the Experience Editor as well:
ContentBlock.tsx looks like this:
import { Text, RichText, Field, withDatasourceCheck } from '@sitecore-jss/sitecore-jss-nextjs';
import { ComponentProps } from 'lib/component-props';
type ContentBlockProps = ComponentProps & {
fields: {
heading: Field<string>;
content: Field<string>;
cssClass: Field<string>;
};
};
/**
* A simple Content Block component, with a heading and rich text block.
* This is the most basic building block of a content site, and the most basic
* JSS component that's useful.
*/
const ContentBlock = ({ fields }: ContentBlockProps): JSX.Element => (
<div className="contentBlock">
<Text tag="h2" className="contentTitle" field={fields.heading} />
<RichText className="contentDescription" field={fields.content} />
<Text tag="p" field={fields.cssClass} />
<pre>
<code>{JSON.stringify(fields, null, 2)}</code>
</pre>
</div>
);
export default withDatasourceCheck()<ContentBlockProps>(ContentBlock);
Let me know if you have any questions/thoughts or if you find a better approach.
Happy coding! :)
| JSS template field names: how to automatically serialize field names in camelCase?
I want to do the following:
Name template fields in the format "My Field Name"
Avoid filling out Display Name fields for each template field
Automatically serialize the field names in camelCase when returning the data from the Layout Service
Where
"fields": {
"Page Size": {
"value": 3
}
}
Becomes
"fields": {
"pageSize": {
"value": 3
}
}
By default, Sitecore does not do this -- it will serialize the field names literally, spaces included. This previous question about template field name conventions in JSS was helpful. The accepted recommendation was to use camelCase for the actual field names in conjunction with display names to make it readable for content authors. This works, but creates what could be considered unnecessary overhead. Further, this approach can be cumbersome when working with legacy codebases.
I have a temporary solution, but I am concerned about the maintainability because I have overridden the Layout Service Field Serializers with a single line of additional code (and had to do so for each field type):
namespace Website.Foundation.LayoutService.Serialization.FieldSerializers
{
public class NumberFieldSerializer : Sitecore.LayoutService.Serialization.FieldSerializers.NumberFieldSerializer
{
public NumberFieldSerializer(IFieldRenderer fieldRenderer) : base(fieldRenderer) { }
public override void Serialize(Field field, JsonTextWriter writer)
{
...
writer.WritePropertyName(field.Name.ToJsonPropertyName());
...
}
}
}
I'm looking for a maintainable approach to do this automatically.
To clarify, it's not that I am completely opposed to using Display Name, or rather the Title field of template fields to make them readable to content authors; it's that retrofitting it for hundreds of items becomes rather tedious. Automatic model generation is also a factor. A modern JSS solution written in TypeScript ostensibly calls for automatic model generation both in .cs and .ts files. Variable name format conventions are not the same across languages / frameworks.
The core of this question touches on best practices for C#, JS, Helix, and content authoring in terms of variable / label names.
For example, given a field item named My Field Name, we have these requirements depending on where it's used:
JSS: myFieldName
C#: MyFieldName (where SomeModel.MyFieldName = {GUID})
Content Author: My Field Name
There is no best solution. Each approach will involve code or configuration. The question stands: given a field named My Field Name, what is the most maintainable way to automatically serialize the field name in the format myFieldName in the Layout Service?
| |
It's working fine with.Net Framework 4.8 Web application. It's a reference issue with dlls/version of dll. I think You need to add a Nuget package reference of Sitecore.Kernel as per your Sitecore version into the project. IServicesConfigurator interface is a part of Sitecore.DependencyInjection namespace and part of Sitecore.Kernel.Dll.It would install relative dependencies of DI DLLs like below.
You can remove all the references you added and add Sitecore.Kernel from the Nuget package and create ServicesConfigurator class.
using Sitecore.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace XX.Website
{
public class ServicesConfigurator : IServicesConfigurator
{
public void Configure(IServiceCollection serviceCollection)
{
//Code here
}
}
}
| IServicesConfigurator not found
My Sitecore web application is a .Net Framework 4.8 Web application. I am trying to integrate Sitecore DI container.
I have added Nuget packages for Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.DependencyInjection.Abstraction and Sitecore.DependencyInjection.
I have written ServicesConfigurator class looking at example here. For some reason,
IServicesConfigurator is not getting resolved. Please refer to the attached image.
Can anyone please help? Is it because I am using .Net Framework 4.8 Web application? I dont think so.
Thanks in advance.
| |
Set the Build and Deploy Settings in Configuration Manager. Select your project and check Build checkbox in your active solution configuration that is selected in the above first dropdown. Do this for all of the build configurations.
Try if this works for you.
Check this for more reference - https://blogs.perficient.com/2013/12/08/setting-up-a-sitecore-solution-part-2-tds-and-build-configurations/
| New project is not included in local publish using TDS
I'm working on an existing Visual Studio solution which uses TDS.
I have added a new class library project in the Foundation layer namely MyProject.Foundation.Accounts. This project is not referenced in any of the other projects. It is only used in a patch config.
When I right-click on the Solution and choose Deploy Solution to publish files in my local instance, the new dll MyProject.Foundation.Accounts.dll is not published.
There is a MyProject.Build TDS project. When I check its properties (General), the Source Web Projects field lists all projects except for the new one.
How to include my new project and also, should the step be done for every new project.
Update :
The Configuration properties has Build checked and Deploy disabled for both Release & Debug.
| |
The field CreatedBy is system defined and read-only. You may not be able to edit the system-defined fields. You can create your own field by updating the schema and putting the user information.
| Linking an asset's CreatedBy field to another user in Content Hub
Is it possible to re-link an Asset's CreatedBy field to another user?
I am aware that this is a system field and possibly uneditable but still would like to know if this is possible at all, either via UI or programmatically.
I played around the REST API and from the looks of it, there's no straightforward way of doing it provided by the documentation.
| |
$startDate = [DateTime]"2023-1-01"
$endDate = [DateTime]"2023-1-12"
Get-ChildItem -Path "master" -ID "ITEM ID here" -Recurse | Where-Object { ($_.__Updated).Date -ge $startDate -and ($_.__Updated).Date -lt $endDate} | Select-Object -Property Name, __Updated, @{Label="Path"; Expression={$_.Paths.FullPath}}
| Powershell script to get the list of items created/modified on particular day
We would like to pass the particular day and get the list of items changed on that day. Do we have any PowerShell script for that?
| |
Please make sure the format of Field Name is correct - it should be similar to Solr field name (lowercase and with underscores instead of spaces) but without the field type suffix.
For example, if a text field is called "Title" in Sitecore, you should specify title instead of title_t.
You can also check Search.log for any error or info messages - usually there is a log message if something is wrong with a facet.
| Newly created Facet is not showing in Content Search view
I created a facet as per the documentation: https://doc.sitecore.com/xp/en/developers/92/sitecore-experience-manager/facets.html
In the "Field Name" field I tried the field name as in the item's template and also as in the Solr index. Neither worked.
How do I make it show up in the Sitecore Content Search? Are there any additional settings I have to do?
| |
The answer is... It depends:
If you are on XM then there is no need for it, you should be tracking analytics and personalizing via a composable solution, Google Analytics, Sitecore Personalize etc...
Do you use xDB and want to track analytics with XPs feature set? If so, that's the process to do it.
The caveat to that is, do you really need XP in a headless world, it reduces the feature set you can use in headless. For example if you are building with Next.js, your pages need to be SSR not SSG, which is losing performance.
| Is Visitoridentification relevant in Sitecore Jss based Implementation?
Visitoridentification is important in Asp.Net MVC-based implementation, but I'm curious if Sitecore Jss-based implementations also require this to be enabled.
I observe that the Sitecore CD server is receiving a lot of requests for visitor identification. Can you advise if it would be best to disable this in the JSS implementation?
| |
Sorry for answering here so quickly, but I got the fix; basically, while doing the import, we have to choose all repositories and can't choose a selected repository. My problem was resolved after importing the entire repository. Thank you all.
| Invalid repository selection. Creating a new connection will require 'All repositories' access to automate the repository creation process
I was doing the XM Cloud setup, and while importing a GitHub repository, I got the below error. Let me know if anyone else got the same issue and what the fix was.
| |
I wouldn't remove any of the built-in indexes, as Sitecore (may) use them internally. For example if an editor switches to web in the Content Editor, you don't want potential exceptions in the UI.
But since you really don't care about the content of that index in this scenario, I'd change the crawler to index less content, such as just selected item paths or exclude just the Media Library. This will speed up crawling and reduce the size of you web index. Also consider setting <indexAllFields> to false unless you've already done so. Sometimes such small change would speed up things enough.
You can also change the indexing strategy to manual so that Sitecore doesn't spend resources on keeping the index up-to-date. Thereby you keep the index functionality and you can rebuild it your self if you ever need it in the future. It could for example be a scenario where you want to do a one-off carve among published data to build a report or something. Basically, everything works as default, but you'll have outdated data. There's almost always a small percentage of outdated data in the indexes anyway.
I'd also recommend you to poke around a bit in the Search.log files just to be sure you don't have any dependency on the web index. Just search for sitecore_web_index as the index name is always a part of the logged query.
| Is Sitecore_Web_Index mandatory?
I have a Sitecore (9.3) JSS based Multisite environment (10+ regional sites). Each site has a separate index, as well as the Sitecore Web index and Sitecore Master index.
The Sitecore Web index now contains more than 1 million documents, 20% of which are Sitecore content and 80% of which are media library items. As a result, the index rebuild takes longer, which affects the performance of index rebuild. Appreciate your inputs on the following.
If not used in any searches, is it still necessary to index the media
items (in Sitecore_web_index or Sitecore_master_index)?
Given that we already have a distinct sitewide index, can you see any limitation
on completely turning off this Sitecore_web_index?
| |
I did the same setup of Razl on my local for Sitecore 10.1 version. Here is my script.
import-module "C:\Program Files (x86)\Sitecore\Razl\HedgehogDevelopment.RazlClient.dll" -verbose
[System.Environment]::SetEnvironmentVariable('RAZL_LICENSE_KEY','my-license-key')
$connection = Get-RazlConnection -SitecoreWebUrl 'https://sitecore10.1sc.dev.local/' -DatabaseName master -AccessGuid '8d92797d-2d19-4ec5-a4f1-b10750c98872'
Get-RazlItem -Connection $connection -ItemID "{27F07929-9DF9-4E3E-9AC3-809AE7EBACCA}"
And I am able to get a response like this.
After investigating, I found a similar issue mentioned in the article. So according to the article if the error you see of Razl License is like this.
An error occurred when checking for a license @ . The error message is: The activation was rejected by the server.
The issue will be this.
Razl also logs information for problems occurring when communicating with the license server or the license key. If you see the above error, there's probably another installation of Razl using the same license key, or there's a problem with the key itself. In this case, please contact the Hedgehog support team.
Read more
https://www.teamdevelopmentforsitecore.com/Blog/razl-log-files
So the script is working fine and the issue is with your license.
Thanks
| Sitecore Razl Script connection error
I am starting the Sitecore Razl scripting and trying to get an item by using script as mentioned in the documentation.
https://hedgehogdevelopment.github.io/razl/script.html
So my script goes like this:-
import-module "C:\Program Files (x86)\Sitecore\Razl\HedgehogDevelopment.RazlClient.dll" -verbose
[System.Environment]::SetEnvironmentVariable('RAZL_LICENSE_KEY',<MyLicenseKey>)
$connection = Get-RazlConnection -SitecoreWebUrl <MySitecoreWebUrl> -DatabaseName master -AccessGuid <myAccessGuid>
Get-RazlItem -Connection $connection -ItemID "{6A148A08-B363-4C50-9DE7-6F38GHI054JK}"
and getting the below error :-
Get-RazlItem : The activation was rejected by the server.
At line:5 char:1
+ Get-RazlItem -Connection $connection -ItemID "{6A148A08-B363-4C50-9DE ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-RazlItem], LicenseFailureException
+ FullyQualifiedErrorId : GetItem: An error occured when checking for a license @ 1/13/2023 3:32:12 AM. The error message is: The activation was rejected by the server..,HedgehogDevelopment.RazlClient.CmdLets.GetItem
Get-RazlItem : Could not find Razl License. Please run Razl.exe and add/update your license.
Any ideas or thoughts on why this error is coming up?
| |
Here is my take on this but it would be interesting to hear if anybody else had experience with this too.
Technically it is enough to set Xdb.Enabled and Xdb.Tracking.Enabled to "false" to stop Sitecore from running XP tools and features. However, usually we also want to remove all XP-specific roles and resources when performing a downgrade to reduce unnecessary hosting and maintenance costs.
It is possible to remove XP resources from connection strings on CM and CD roles, but other configs in /App_Config have dependencies on connection strings so configs will need to be cleaned up too. Otherwise you may get unwanted error messages in logs about unavailable services, databases and indexes.
The easiest way to do the file cleanup is actually to create a fresh XM installation and deploy your project on top of it - with this approach you can be sure that all Sitecore files are correct.
Custom code cleanup is a good practice too - you can start from reviewing project file references to Sitecore libraries and custom configs.
Cleanup of content databases is required only when upgrading to Sitecore 10.1+ from previous versions. This is needed to remove standard Sitecore items that are now stored as resources. So if your website is already on 10.1, then content database cleanup should not be needed.
| How to downgrade from XP to XM
I have a solution on PROD with Sitecore 10.1.1 which has to be downgraded from XP to XM.
I know all the features and things that will be lost, and that part was already taken into consideration.
I have seen these questions Downgrading from XP to XM and Upgrade Sitecore 8.2 XP Database to Sitecore 10.2 XM Database but still, something is not clear to me.
Technically is it enough to disable xDB by having the Xdb.Enabled and Xdb.Tracking.Enabled settings to false? By using a patch file like this one:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Xdb.Enabled" value="false" />
<setting name="Xdb.Tracking.Enabled" value="false" />
</settings>
</sitecore>
</configuration>
Are the following mandatory?
clean up content databases
clean up of files from the disk (Sitecore stock dlls, configs, etc)
clean up things in code (remove/disable some custom code/configs) whare related with xDB/Analytics?
What else should I do besides having the Xdb.Enabled and Xdb.Tracking.Enabled settings to false
What is your take on this?
| |
The Sitecore representative for you or your client can provide the date of occurrence. Once you have that, you can search the Sitecore log for the following lines.:
The maximum number of simultaneously active (logged-in) editors exceeded. The User sitecore\xxx cannot be logged in to the system. The maximum of editors allowed by license is 5.
or for IIS request log manually or through Application Insights(depending on your setup):
2023-01-13 21:20:39 xxx.xx.xx.xxx GET /api/sitecore/BoostUsers/RedirectToBoost - 80 sitecore\Admin
| How to check who changed the user count in sitecore instance
Our current Sitecore license allows 3 concurrent users. Through Boost users screen someone has increased the user count. Is there a way to find who is changing the number of users on the Boost screen and how can we lock it down? Does Sitecore maintains any audit for the same? if so where am I supposed to find it? Do I need to raise Sitecore ticket for the same?
| |
There is no built in functionality to get image from Rendering Parameters. Instead you need to manually load xml and then get image by ID.
This code should get you on right track:
var imageParam = RenderingContext.Current.Rendering.Parameters["image"];
var xml = XmlUtil.LoadXml(imageParam);
var imageId = xml != null ? XmlUtil.GetAttribute("mediaid", xml) : string.Empty;
var imageItem = Context.Database.GetItem(new ID(imageId));
| Get image from rendering parameters
I am using rendering parameters to render the image in view.
It is showing :-
<image mediaid="guid"/>
Instead of the image. Kindly assist me.
| |
If you want to know if it's possible to host xDB databases on the same servers as the content database then the short answer is yes.
But then there are other things to consider like scalability. If you do not foresee any substantial increase in the xDB data (like adding new sites or getting new users in by adding more languages to existing websites) then you may go for setting up in the same server. But in the longer term, it might be beneficial to separate it out for scalability as well as troubleshooting purposes in case there are issues.
Note: Separate server means additional cost of License as well. Since your site is having a traffic of 320K page request/day, separate server is the correct way while upgrading.
| Hosting xDB on same database server as content database (OnPrem)
We are currently upgrading from 10.0 to 10.3 (on prem). Since MongoDB for the Experience Platform is no longer supported, we are attempting to set up our xDB on SQL. The SQL server that we currently have hosts our content database. Does anyone have experience hosting their xDB on the same server or should we spin up entirely separate servers for these? (as a side note, we get approximately 320k page requests/day)
| |
CD server should not have access to master index and no configurations for it. To fix this issue you can add role:require="Standalone or ContentManagement" to your master index as below:
<sitecore search:require="solr">
<contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes>
<index id="sitecore_master_index" role:require="Standalone or ContentManagement" >
<enableItemLanguageFallback>true</enableItemLanguageFallback>
<enableFieldLanguageFallback>true</enableFieldLanguageFallback>
</index>
<index id="sitecore_web_index">
<enableItemLanguageFallback>true</enableItemLanguageFallback>
<enableFieldLanguageFallback>true</enableFieldLanguageFallback>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
| Solr error on adding patch for fallback language
I am using Sitecore 10.2 with SXA.
I have added a patch file for fallback language in solr. When I deploy this patch file,on CM server it works fine but on CD server I get the error. Could not find method: AddIndex.(Screenshot attached).
Please suggest what could be missing.
Patch file code:
<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 search:require="solr">
<contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes>
<index id="sitecore_master_index">
<enableItemLanguageFallback>true</enableItemLanguageFallback>
<enableFieldLanguageFallback>true</enableFieldLanguageFallback>
</index>
<index id="sitecore_web_index">
<enableItemLanguageFallback>true</enableItemLanguageFallback>
<enableFieldLanguageFallback>true</enableFieldLanguageFallback>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
</configuration>
| |
Your screenshot shows:
It means there are in total 14383 documents in solr (you can treat that as number of versions of items in any language).
You can also see that you only ask Solr to return first 10 results:
That's why you don't see your items.
If you want to make sure that your item really is indexed, you can run a query with _group key and use item id (lowercase, without - and without curly brackets). That will return all the versions of that single item from the index, e.g.
_group:110d559fdea542ea9c1c8a5df7e70ef9
| Solr results not showing all content items in portal
Using Sitecore 10.1.2
This is a fresh instance and I have created a few templates and some related content items.
I have rebuilt the indexes for sitecore_master_index & sitecore_sxa_master_index.
In the Solr portal, when I select either of them in core and run a query with no filters, it shows only one of the new content items.
I'm expecting it to list all the created items.
Have not created any custom indexes or any custom code related to search.
What should I configure to see all the content items in the search results.
| |
With the help of @MichaelWest and @benlipson I've identified the issue and have 2 solutions. Well really 1 workaround and 1 hack.
(solution; actually this didn't fix it.. but good practice anyway) Ben pointed out that I was calling GetSynthesisQueryable<> with type IStandardTemplateItem for no good reason. Instead I refactored my code with generics so the actual Type I wanted back was used. This resolved the issue.
(workaround) If you for some reason can't do this sort of refactor or your case is caused by something slightly different, try changing the ContentSearch.Solr.MaxNumberOfFieldsToProject setting to "0". This worked for me also.. but the refactor is definitely the preferred method.
(hack) Another way to fix this is to modify the template that generates all your Synthesis models so that they each include a new property that maps to the _template index field. For example:
public interface IAlertsDictionaryItem : IStandardTemplateItem
{
[IndexFieldAttribute("_template")]
ID Template { get; set; }
// ...
}
public class AlertsDictionary : StandardTemplateItem, IAlertsDictionaryItem
{
// ...
[IndexFieldAttribute("_template")]
public ID Template { get; set; }
// ...
}
| Synthesis Solr search not returning strongly typed implementations after upgrade
I'm upgrading a Sitecore 9.3 solution to Sitecore 10.2. The solution uses Unicorn, Leprechaun, and Synthesis for ORM. As part of the upgrade, Synthesis was updated from 9.1.0.0 to 9.1.6.0.
Everything seems to work except for Synthesis SOLR search.
C#
using (var context = ContentSearchManager.CreateSearchContext(new SitecoreIndexableItem(settingContainer.InnerItem)))
{
indexname = context.Index.Name;
var hits = context.GetSynthesisQueryable<IStandardTemplateItem>()
.Where(x => x.AncestorIds.Contains(settingContainer.Id))
.Where(x => x.TemplateIds.Contains(settingTemplateID))
.GetResults()
.Hits;
setting = hits.FirstOrDefault()?.Document;
// 'setting' used to return a strongly typed implementation of the underlying item if available
// so I could do this:
var x = setting as ISiteHeaderItem
}
The setting variable now gets back a StandardTemplateItem object instead of the strongly typed object I used to get before the upgrade.
Digging through the Synthesis.Solr source code I found the spot where it should be mapping the search result to my strong type. Debugging with this leads to a confusing result:
Line 20 makes the call to the mapper which instantiates the strong type. However, it performs this mapping by reading the _template field of the document from the SOLR result. As you can see from the screenshot, there is no _template field.
Does anyone know why? And/or how to resolve this?
Things I have tried:
Re-Populated SOLR Managed Scheme
Re-Indexed all SOLR indexes
| |
This issue is due to firewall settings and network policy settings on your development machine. Couple of things to try:
Ensure that the Use Docker Compose V2 option is not checked and Use the WSL 2 based engine is checked in Docker Desktop.
Bypass some common network issues by setting DNS servers in the Docker engine configuration and switching the buildkit to false
{
"dns": [
"8.8.8.8"
],
"experimental": false,
"features": {
"buildkit":false
}
}
DNS Flush on your development machine: In the command prompt window, type ipconfig /flushdns You should see a message confirming that the DNS Resolver Cache was successfully flushed.
If none of the above options works, install nodejs manually as explained here. Run the set up again.
| NodeJs Container Build in Xmcloud Foundation head
Trying to work through the xmCloud Foundation head - https://github.com/sitecorelabs/xmcloud-foundation-head-staging#deploy-to-xmcloud and install locally using Docker. But getting this error on container build.
Step 6/12 : RUN curl.exe -sS -L -o node.zip https://nodejs.org/dist/v%NODEJS_VERSION%/node-v%NODEJS_VERSION%-win-x64.zip
---> Running in 76a734f4d2f7
hcsshim::CreateComputeSystem 76a734f4d2f7a6afe9a59e9b215037eaa70f324a295141e2a228759f787a2d5a: The request is not supported.
ERROR: Service 'nodejs' failed to build : Build failed
D:\PlayArea\xmCloud\xmcloud-foundation-head-staging\up.ps1 : Container build failed, see errors above
Do I need to disable anything specific? I have checked for instances where C:\ is present and changed it to lowercase
| |
We created a sitecore ticket for that and after few conversations we were able to resolve that.
The issue is caused due to the following:
When an asset is deleted via the asset details page, it is actually "soft deleted". This means that the asset can still be recovered.
In this case, the asset's public links are not deleted from the system, they are just disabled.
The public link is only deleted after the asset is "hard deleted". You can go to Manage > Trash to see all the assets that are currently "soft deleted".
Items in trash will be permanently deleted after 30 days.
You need to "hard delete" the incorrect asset and then re-upload the file. The script works after "hard deleting" the file.
We have tested this and was able to run the script with success
| Issue while creating a public link of an assest
We are creating a public link of an asset through an action script whenever an asset is modified.
The format of the public link is "Content hub domain/CDN name" + "Rendition name" + "Filename" which means Public URL is generated based on the filename.
Note: If there is already a filename with a public URL then the second instance of same filename will not be able to generate a public URL, which is fine but in some cases, we had to delete the old image and replace it with the updated correct image, in that case also Content hub is giving error while creating a public link.
The specified target is invalid. Exception:
Stylelabs.Scripting.Exceptions.RuntimeException: The script execution
failed in runtime - The specified target is invalid. --->
Stylelabs.M.Sdk.Exceptions.ValidationException: The specified target
is invalid. Failures: Property: 'RelativeUrl'.: ‘{RelativeUrl}’
already exists Stack trace: at
Stylelabs.M.Sdk.ScriptClient.Clients.EntitiesClient.SaveAsync(IEntity
entity) in
/src/Stylelabs.M.Sdk.ScriptClient/Clients/EntitiesClient.cs:line 176
at Submission#0.<CreateForRendition>d__15.MoveNext() in :line 195 ---
End of stack trace from previous location where exception was thrown
--- at Submission#0.<<Initialize>>d__0.MoveNext() in :line 66 --- End of stack trace from previous location where exception was thrown ---
at
Stylelabs.Scripting.Engines.CSScript.Persistence.<>c__DisplayClass10_0`1.<<Load>b__0>d.MoveNext()
in /src/Stylelabs.Scripting/Engines/CSScript/Persistence.cs:line 222
--- End of stack trace from previous location where exception was thrown --- at Stylelabs.Scripting.Script`1.Run(Object
globalScopeObject) in /src/Stylelabs.Scripting/Script.cs:line 255 ---
End of inner exception stack trace --- at
Stylelabs.Scripting.Script`1.Run(Object globalScopeObject) in
/src/Stylelabs.Scripting/Script.cs:line 259 at
Stylelabs.M.Base.Scripting.Base.ScriptSubCacheBase.Execute(CachedScript`1
script, Func`4 scopeHandler, Func`4 resultHandler) in
/src/Stylelabs.M.Base/Scripting/Base/ScriptSubCacheBase.cs:line 469
However, when we try to browse the existing URL, we get a 404 error.
Is there any cache thing in content hub which prevents content hub to create a public link for that asset?
Update : Added error in text format, so that it will be useful for SEO.
| |
We encountered a problem very similar to your question. We started experiencing the issue once upgrading to 10.3 and CLI 5.1.25. In our case, the problem was caused by using a relative file path in defaultModuleRelativeSerializationPath like ../../serialization in the project's sitecore.json file.
When using ser pkg create this causes the package to construct a corrupted file path for serialized roles within the package (zip) file. Thus the roles are interpreted as empty by ser pkg install, dropping all the roles afterward.
Package file opened with WINRAR to see file contents
The solution for us was not very straight forward since:
The construction with pkg create and install ran apparently stable for a long time.
You can override file path serialization on the module level, however, you cannot do that for roles.
Changing it in the root sitecore.json will cause issues for all modules.
We ended up adding a new sitecore.json config file to the project. In there correcting the defaultModuleRelativeSerializationPath to just "serialization" and moving the serialized roles into the folder where the actual module is located. Afterwards calling ser pkg create with the extra --config parameter referencing the duplicated sitecore.json file for creating an itempackage just for roles.
| Sitecore serialization package installation removes custom roles
There is a Sitecore 10.2 instance with serializations delivered via Sitecore.CLI v4. Item changes delivered via package and installed using the following command:
dotnet sitecore ser pkg install -f "$(System.ArtifactsDirectory)\serialization.itempackage" --client-id "$(sitecoreClientId)" --client-secret "$(accSitecoreClientSecret)" --cm "$(accSitecoreContentManagementHost)" --auth "$(accSitecoreIdentityHost)" --publish
The package contains custom security roles that inherit standard Sitecore ones (like Author etc.). When the roles were included into package for the first time, they were successfully delivered to CM. After few deployemts (not the next one), package installation kills them:
[role] [D] Role ***\MyProj Content Editor is removed successfully
[role] [D] Role ***\MyProj Limited Content Editor is removed successfully
The roles are still in the package under <module-name>/items/_roles/sitecore directory. The serialization files look the same as in the initial package. What may cause such a behavior?
| |
A few things you can try out to speed up local instances are as followed.
Add optimizeCompilations=”true” to the compilation tag in web.config.
<compilation defaultLanguage="c#" debug="false" targetFramework="4.6.2”>
With
<compilation defaultLanguage="c#" debug="false" targetFramework="4.6.2" optimizeCompilations="true">
In Sitecore.Xdb.config located in \App_Config\Sitecore\Marketing.xDB turn off tracking and analytics by setting Xdb.Enabled and Xdb.Tracking.Enabled to false
Turn off device detection in \App_Config\Sitecore\DeviceDetection.Client\Sitecore.CES.DeviceDetection.config by setting DeviceDetection.Enabled to false
Patch the configuration to make sure the agent doesn’t run every 10 seconds. It appears to be related to list management.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore role:require="Standalone or ContentManagement">
<scheduling>
<agent type="Sitecore.ListManagement.Operations.UpdateListOperationsAgent, Sitecore.ListManagement">
<patch:attribute name="interval">00:30:00</patch:attribute>
</agent>
</scheduling>
</sitecore>
</configuration>
refer this for more details: https://www.symsoftsolutions.com/sitecore/tips-to-make-sitecore-load-faster-on-development-machines/
hope it helps!
| Site load takes 30 minutes after deploying DLL into local instance
Using Sitecore 10.1.2
Whenever I deploy a custom DLL into my local instance, the first page load takes more than 30 mins.
It could be any DLL. I publish them in debug mode and there are no *.pdb files.
I do not see any errors in the log.
How should I go about troubleshooting this or is there any way to improve the page load speed.
| |
There is a great article created by Martin, where he shared something about the customization and the way we can deploy it to XM Cloud. According to the article, it is possible to customize XM Cloud in a similar way as we did it with XP by applying patches, but there is an expectation is that developers would customize less and less with time and platform growth. From the functionality point of view, these customizations would focus on data and synchronization rather than patching system features.
You can read the full article here.
https://blog.martinmiles.net/post/ultimate-guide-to-XM-Cloud
You can apply config patches for configuring CM instance, the same as you did before with XP. And here the guide to do that
https://doc.sitecore.com/xmc/en/developers/xm-cloud/deploy-customizations-to-the-xm-cloud-environment.html
| Does Sitecore XM Cloud support custom code e.g. scheduled tasks, computed index fields
What support does Sitecore XM Cloud have for custom code within the CM role (such as computed index fields, scheduled tasks etc)?
| |
An attempt to utilize static prop PageContext.Current indeed can be cumbersome. While it is an Ambient Context, Sitecore implementation does not let you mock and set it easily. Even if you do, you'll get concurency issues running your tests in parallel.
A better approach would to inject an instance of PageContext in the code where you wanted to use static PageContext.Current prop. The PageContext can be easily mocked and configured. See below.
PageContext.Item property has a public setter. Just set the item there and that's it:
[Theory, AutoNSubstituteData]
public void PageContextItemTest(
[Substitute] PageContext pageContext,
Item current)
{
pageContext.Item = current;
Assert.Same(current, pageContext.Item); // pass
}
There is a list of customizations that simplify the Item creating using AutoFixture and AutoFixture.AutoNSubstitute libraries:
public class AutoNSubstituteDataAttribute : AutoDataAttribute
{
public AutoNSubstituteDataAttribute()
: base(() => new Fixture()
.Customize(new AutoNSubstituteCustomization())
.Customize(new DatabaseCustomization())
.Customize(new ItemCustomization())
.Customize(new FieldCustomization()))
{
}
}
internal class DatabaseCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Inject(Substitute.For<Database>());
}
}
internal class ItemCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<Item>(x =>
x.FromFactory(() => CreateItem(fixture))
.OmitAutoProperties()
);
}
private static Item CreateItem(ISpecimenBuilder fixture)
{
var item = Substitute.For<Item>(
fixture.Create<ID>(),
ItemData.Empty,
fixture.Create<Database>());
item.Name.Returns("item_" + fixture.Create<string>());
item.Children.Returns(Substitute.For<ChildList>(item, new List<Item>()));
item.Fields.Returns(Substitute.For<FieldCollection>(item));
var language = Language.Parse("en");
item.Language.Returns(language);
item.Languages.Returns(new[] { language });
var template = Substitute.For<TemplateItem>(Substitute.For<Item>(
fixture.Create<ID>(),
ItemData.Empty,
fixture.Create<Database>()));
item.Template.Returns(template);
item.Version.Returns(Version.First);
item.Versions.Returns(Substitute.For<ItemVersions>(item));
item.Versions.Count.Returns(1);
return item;
}
}
internal class FieldCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<Field>(x =>
x.FromFactory(() => CreateField(fixture))
.OmitAutoProperties()
);
}
private static Field CreateField(ISpecimenBuilder fixture)
{
var item = fixture.Create<Item>();
var field = Substitute.For<Field>(
fixture.Create<ID>(),
item);
field.Database.Returns(item.Database);
return field;
}
}
UPDATE
The customaizations above are samples. They mock items and props and let you extend it further as needed. For instance, if you need some template id, you can extend the ItemCustomization Create method with the following line and generate random id:
item.TemplateID.Returns(fixture.Create<ID>());
If you need a specific template Id in your test, you can set it in the test:
[Theory, AutoNSubstituteData]
public void SetCustomTemplateId(Item item, ID expected)
{
item.TemplateID.Returns(expected);
Assert.Same(expected, item.TemplateID);
}
Same about verstions.
| How do you unit test PageContext.Current.Item?
I'm currently creating a unit test for an action result method:-
public virtual ActionResult MyControllerTest(){
var pageItem = PageContext.Current.Item
...
return ViewOrErrorResult<string>(null);
}
Unit test goes like this:-
[Theory, AutoData]
public void MyControllerTest_Results(params){
//assign
var pageContext = Substitute.For<PageContext>();
ContextService.Get().Push(pageContext);
//Act
...
//Assert
}
However, PageContext.Current.Item is always null. Anyone has tried mocking PageContext.Current.Item?
Thanks
| |
The recommendation is to use Sitecore powershell extensions instead of SPEAK.
https://doc.sitecorepowershell.com/interfaces/interactive-dialogs
| Sitecore Speak Visual Studio 2022
I need to make a Sitecore Speak application in Visual Studio 2022. Last time I did this in a project in VS2019, I used "Sitecore Rocks" - but I get an error when I try to install Sitecore Rocks in VS2022. It seems it is not compatible.
How do I make Speak applications in Visual Studio 2022?
Thanks.
| |
Solution 1:
I suspect it has something to do with the version of JSS that you are using, or perhaps has to do with your operating system or line endings.
I found this discussion on GitHub that mentions the exact error you are experiencing:
https://github.com/Sitecore/jss/issues/29
The implication of the above is that you may need to update your version of JSS.
Solution 2:
Verify that scjss-verify-setup is defined somewhere.
For example, the main JSS repo, defines the following in jss/packages/sitecore-jss-dev-tools/package.json:
"bin": {
"scjss-verify-setup": "./dist/cjs/bin/verify-setup.js"
},
Verify that the command is defined and that the file it is referencing exists. The safest bet would be to do a "find all" on your entire directory.
Solution 3:
Delete node_modules and run npm install again.
Additional Questions:
Which version of JSS are you using?
Which version of the JSS-CLI are you using?
Which OS are you using?
| jss start:connected mode error 'scjss-verify-setup' is not recognized as an internal or external command
I did a NPM install and it broke my jss start:connected mode.
I type jss start:connected and then it errors out. In the Package.json file it errors out on
"start:connected": "scjss-verify-setup && npm-run-all --serial bootstrap:connected --parallel theme-watch start:angular start:watch-components",
The error that shows up
'scjss-verify-setup' is not recognized as an internal or external command,
operable program or batch file.
I have attached a pic below that tells what versions I have.
| |
This is not an Azure Search problem. You can use the ContentSearchAPI to filter your results based on the path of the items returned.
using (var context = ContentSearchManager.GetIndex("sitecore_master_index").CreateSearchContext())
{
// Create an initial predicate - use .True<T> since we'll be AND'ing this clause together with the search query
var filterPredicate = PredicateBuilder.True<SearchResultItem>();
// Filter by site
filterPredicate = filterPredicate.And(x => x.Path.Contains("/sitecore/content/yoursite/home/path"));
// Add your search query to the predicate
fitlerPredicate = filterPredicate.Where(x => ......);
// Fetch results from the search index using the predicate
var results = context.GetQueryable<SearchItemResult().Filter(filterPredicate);
}
This will limit the search results to a single sites content. Of course you can get more finely grained if you need to only search within a specific section of content.
| Sitecore 9.3 Azure Search multi-site search with separate indexes
Using Sitecore 9.3 and Azure search. We have a single Sitecore CM instance setup with two content trees:
/sitecore/content/siteOne
/sitecore/content/siteTwo
We have separate CD sites for each of the above sites. When a user searches in siteOne, we only want results from siteOne's content tree, and likewise for siteTwo.
Is this even possible? I've searched StackExchange and the Sitecore Community for examples - any examples of how to set this up, and I am not finding anything.
| |
I got the response from Product team and they mentioned that the url we are passing in the request is not correct and Documentation has to be updated by Sitecore Docs team.
Here is the correct curl request.
curl --request POST --url "https://auth.sitecorecloud.io/oauth/token" --header "content-type: application/x-www-form-urlencoded" --data grant_type=client_credentials --data client_id=<clientid> --data client_secret=<clientsecret> --data audience=https://api.sitecorecloud.io
Woohoo, i tried with this, and it worked.
| Always getting 404 Not Found response when trying to generate JWT token for XM Cloud via authentication clients
As per the documentation https://doc.sitecore.com/xmc/en/developers/xm-cloud/managing-xm-cloud-authentication-clients.html, I created a Authentication Client in XM Cloud Deploy App at the Organization level and i got the Client ID and Client Secret.
As a next step, i tried to get JWT token by following this document https://doc.sitecore.com/xmc/en/developers/xm-cloud/request-a-jwt-for-the-cm-instance-using-oauth.html, and run curl command like below.
curl --request POST --url "https://auth.sitecorecloud.io" --header "content-type: application/x-www-form-urlencoded" --data grant_type=client_credentials --data client_id=<clientid> --data client_secret=<clientsecret> --data audience=https://api.sitecorecloud.io
But i always get 404 Not Found response back.
Am i doing something wrong here?
Is there any other way to generate JWT token to trigger XM Cloud APIs?
| |
The only way I could get this to work was by changing the configuration in code when the application starts.
Firstly, create a class that can modify the machine keys section using app settings.
public class MachineKeys {
public MachineKeys(string encryptionKey, string validationKey) {
this.DecryptionKey = encryptionKey;
this.ValidationKey = validationKey;
}
public string Decryption { get; set; }
public string DecryptionKey { get; }
public string Validation { get; set; }
public string ValidationKey { get; }
public static void InstallKeysFromAppSettings()
{
Install(GetKeysFromAppSettings());
}
public static void Install(MachineKeys keys)
{
if (keys == null)
{
return;
}
var getter = typeof (MachineKeySection).GetMethod("GetApplicationConfig", BindingFlags.Static | BindingFlags.NonPublic);
var config = (MachineKeySection) getter.Invoke(null, Array.Empty < object > ());
var readOnlyField = typeof (ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
readOnlyField.SetValue(config, false);
config.DecryptionKey = keys.DecryptionKey;
config.ValidationKey = keys.ValidationKey;
if (!string.IsNullOrEmpty(keys.Decryption))
{
config.Decryption = keys.Decryption;
}
if (!string.IsNullOrEmpty(keys.Validation) && Enum.TryParse(keys.Validation, out MachineKeyValidation parsedMachineKeyValidation))
{
config.Validation = parsedMachineKeyValidation;
}
readOnlyField.SetValue(config, true);
}
public static MachineKeys GetKeysFromAppSettings()
{
var encKey = ConfigurationManager.AppSettings["MachineDecryptionKey"];
if (string.IsNullOrEmpty(encKey))
{
return null;
}
var valKey = ConfigurationManager.AppSettings["MachineValidationKey"];
if (string.IsNullOrEmpty(valKey))
{
return null;
}
var decryption = ConfigurationManager.AppSettings["MachineDecryption"];
var validation = ConfigurationManager.AppSettings["MachineValidation"];
return new MachineKeys(encKey, valKey)
{
Decryption = decryption,
Validation = validation
};
}
}
Then create a pipeline processor class that uses this
public class Processor
{
public void Process(PipelineArgs args)
{
MachineKeys.InstallKeysFromAppSettings();
}
}
And patch this into the initialize pipeline.
You can then set the following app settings, with secret substitution if you need it.
MachineDecryption
MachineDecryptionKey
MachineValidation
MachineDecryptionKey
| Setting Machine key on Managed Cloud / AKS (v10.2)
We noticed on our upgraded 10.2 site that some session based functionality stopped working reliably when having more that one replica. Redis is used for storing session data and is getting populated correctly.
The issues seemed to be with the machine key, which must be different per replica. To solve this we were able to add the machinekey element in the web.config.
<machineKey
validationKey="..."
decryptionKey="..."
validation="SHA1"
decryption="AES"
/>
The sites reliably work with this fix in, but the issue is that the keys are the same for all of our environments which is a security issue (serious?).
Ideally we'd want to have these stored in keyvault, but I can't find a way to get these values in like we would with AppSettings or ConnectionStrings. I've tried added environment variables, but haven't had any luck so far.
I feel like others must surely have come up against this issue, but I can't find any content online and Sitecore Support have no documentation / advice to give.
How can I set the machine key for all replicas with a configurable method that can be different per environment?
| |
While Debugging the code on local we found that post authentication custom properties of virtual user profile gets removed automatically. We raised a ticket and got an answer from Sitecore Support that it is a known issue and have provided us with a link to hotfix.
Please use the following URL to download the platform pre-release that contains fixes for them:
https://sitecore.service-now.com/kb?id=kb_article_view&sysparm_article=KB1001439
Please refer to the documentation to get more details on how to deploy the pre-release to your solution:
https://doc.sitecore.com/xp/en/developers/102/platform-administration-and-architecture/sitecore-xp-pre-releases.html
| Sitecore user profile Custom Properties not persistant
We have recently migrated from Sitecore 9.3 to Sitecore 10.2. We are facing a very unusual issue. We are having a functionality where the user is getting authenticated using SSO and a virtual user is created in Sitecore. While creating virtual users we are setting 5 custom properties to that virtual user. Post authentication when the user is redirected to the main page, the custom properties of the user profile are not maintained and get removed. We are using "return Redirect()" from that authentication action to the page from which the user initiated login i.e. RelayState.
Thank You In Advance,
Lalit Joshi
| |
Yes, You can customize or extend Sitecore forms elements as per your need. To modify the HTML you can copy RadioButtonList.cshtml file from \Views\FormBuilder\FieldTemplates\ folder.
Create folder structure as \Views\FormBuilder\FieldTemplates in solution and place RadioButtonList.cshtml file and update as bellow.
@using Sitecore.ExperienceForms.Mvc.Html
@model Sitecore.ExperienceForms.Mvc.Models.Fields.ListViewModel
<label class="@Model.LabelCssClass">@Html.DisplayTextFor(t => Model.Title)</label>
@{
var i = 1;
}
@foreach (var item in Model.Items)
{
<label class="">
<input type="radio"
name="@Model.Name"
id="@(Model.Name + "_" + i)"
value="@item.Value" />
@item.Text
</label>
i++;
}
@Html.ValidationMessageFor(m => Model.Value)
Set up the radio button list in the form.
Html output:
<label class="">
<input type="radio" name="custom_text" id="custom_text_1" value="some_static_text_value_1">
some_custom_label_1
</label>
<label class="">
<input type="radio" name="custom_text" id="custom_text_2" value="some_custom_label_2">
some_custom_label_2
</label>
| Experience forms - radio button list
Is it possible to add custom name and id "values" to the list items in the Experience forms "radio button list"?
for now, the name is Sitecore generated guid
We can have custom labels and values but I want the <input> tag HTML to look like :-
<label class="">
<input type="radio"
name="custom_text"
id="custom_text"
value="some_static_text_value"/>
some_custom_label
</label>
| |
Join me down the rabbit hole.
Don't actually follow the steps below. Scroll to the bottom for the recommended solution.
Step 1: Change the Template of a Common Branch Template Parent Item
My branches for page items live under a common parent:
/sitecore/templates/Branches/Project/Main
I changed the template of that item from /sitecore/templates/System/Branches/Branch Folder to /sitecore/templates/Foundation/JavaScript Services/App
Optional steps would be to change the icon back to a folder and to copy the insert options from Branch Folder.
Step 2: Add a New App to Your Site Configuration
The app name is not material, as long as it is unique. I chose to call it branchtemplateeditor.
All this does is register your new App item with JSS.
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<javaScriptServices>
<apps>
<app name="branchtemplateeditor"
sitecorePath="/sitecore/templates/Branches/Project/Main"
graphQLEndpoint="/api/main"
serverSideRenderingEngine="http"
serverSideRenderingEngineEditOnly="false"
serverSideRenderingEngineEndpointUrl="http://localhost:3000/api/editing/render"
serverSideRenderingEngineApplicationUrl="http://localhost:3000"
useLanguageSpecificLayout="true"
defaultWorkflow=""
protectDeveloperItems="false"
deploymentSecret=""
inherits="defaults"
dictionaryDomain="{6336E54C-9D3D-462B-A6F3-CF58C6B16AED}"
/>
</apps>
</javaScriptServices>
</sitecore>
</configuration>
Making this change should recycle your app pool, which is important because there does appear to be caching in play here.
Step 3: Run It
After configuring the workaround, the branch page can be viewed. The URL also pre-populates with the correct sc_site value (in this case main) without any manual action:
https://mysite.sc/?sc_mode=edit&sc_itemid=%7b3xxxxxxxxx%7d&sc_version=1&sc_lang=en&sc_site=main
Conclusion and BEST Solution
The fact that this issue can be remediated by simply creating an App as a parent of the branch template and registering the App in the config appears to indicate that the logic which determines if a ApplicationNotFoundException should be thrown may be rudimentary.
Sure enough, Sitecore.JavaScriptServices.ViewEngine.Presentation.Pipelines.MvcGetRenderer.ResolveAppConfiguration appears to confirm my hunch:
protected virtual AppConfiguration ResolveAppConfiguration(Item contextItem)
{
AppConfiguration appConfiguration = this.AppConfigResolver.ResolveForItem(contextItem);
if (appConfiguration != null)
{
return appConfiguration;
}
if (!contextItem.Name.Equals("__Standard values", StringComparison.OrdinalIgnoreCase))
{
throw new ApplicationNotFoundException(contextItem.Paths.FullPath ?? "(unknown)");
}
return null;
}
This got me thinking. What if I try to view a Standard Values item in Experience Editor?
Bullseye.
If you want to view a branch template in Experience Editor, you must append sc_jssapp=your_app_name to the query string:
https://mysite.sc/?sc_mode=edit&sc_itemid=%7b7b3xxxxxxxxx%7d&sc_version=1&sc_lang=en&sc_site=your_site_name&sc_jssapp=your_app_name
| Experience Editor / preview mode throws error when viewing branch template items
I'm working on a SC 10.2 JSS site. On previous MVC projects I was always able to enter Experience Editor / Preview mode while building branch templates for pages. That is, the items such as /sitecore/templates/Branches/Project/Main/MyPage/$name .
However, I always run into this error:
30960 09:48:43 ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: An unhandled exception occurred.
Source: Sitecore.Mvc
at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.ShowErrorMessage(ExceptionContext exceptionContext, ExceptionArgs args)
at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.Process(ExceptionArgs args)
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.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)
at Sitecore.Mvc.Filters.PipelineBasedRequestFilter.OnException(ExceptionContext exceptionContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at Sitecore.Mvc.Routing.RouteHttpHandler.EndProcessRequest(IAsyncResult result)
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: Sitecore.JavaScriptServices.ViewEngine.RenderingEngine.ApplicationNotFoundException
Message: A Sitecore.JavaScriptServices application was not found for the path /sitecore/templates/Branches/Project/Main/MyPage/$name. You should ensure that:
* You have applied a Sitecore configuration patch for the application (see App_Config\Sitecore\JavaScriptServices\Sitecore.JavaScriptServices.ExampleApp.config.example)
* The path represents a Route
* The Route item is a descendant of an App item
Source: Sitecore.JavaScriptServices.ViewEngine
at Sitecore.JavaScriptServices.ViewEngine.Presentation.Pipelines.MvcGetRenderer.GetJsLayoutRenderer.ResolveAppConfiguration(Item contextItem)
at Sitecore.JavaScriptServices.ViewEngine.Presentation.Pipelines.MvcGetRenderer.GetJsLayoutRenderer.GetRenderer(GetRendererArgs args)
at Sitecore.JavaScriptServices.ViewEngine.Presentation.Pipelines.MvcGetRenderer.GetJssRenderer.Process(GetRendererArgs args)
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.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)
at Sitecore.Mvc.Pipelines.PipelineService.RunPipeline[TArgs,TResult](String pipelineName, TArgs args, Func`2 resultGetter)
at Sitecore.Mvc.Presentation.Rendering.GetRenderer()
at Sitecore.Mvc.Presentation.Rendering.get_Renderer()
at Sitecore.Mvc.Presentation.Rendering.ToString()
at Sitecore.Mvc.Pipelines.Response.RenderRendering.InitializeProfiling.StartProfiling(RenderRenderingArgs args)
at Sitecore.Mvc.Pipelines.Response.RenderRendering.InitializeProfiling.Process(RenderRenderingArgs args)
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.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)
at Sitecore.Mvc.Presentation.RenderingView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)
Aside from this error, I am not finding any helpful information in the JSS/Sitecore logs. When I run in debug mode, I don't see any exceptions getting thrown in my custom code. That makes sense because the error is happening at a much higher level. Everything else is working as expected and I can enter preview/edit mode on regular content items.
Looking at what the error suggests:
The item in question does inherit from the Route template.
The URL for the preview/edit view contains sc_site=main; that is https://mysite.sc/?sc_mode=edit&sc_itemid=%7bxxxxxxxxx%7d&sc_version=1&sc_lang=en&sc_site=main
My config is defined as follows:
<app name="main"
sitecorePath="/sitecore/content/Sites/Main"
graphQLEndpoint="/api/main"
serverSideRenderingEngine="http"
serverSideRenderingEngineEditOnly="false"
serverSideRenderingEngineEndpointUrl="http://localhost:3000/api/editing/render"
serverSideRenderingEngineApplicationUrl="http://localhost:3000"
useLanguageSpecificLayout="true"
defaultWorkflow=""
protectDeveloperItems="false"
deploymentSecret=""
inherits="defaults"
dictionaryDomain="{6336E54C-9D3D-462B-A6F3-CF58C6B16AED}"
patch:source="Sites.config"
/>
It makes sense that an application was not found for the branch template item when it does not exist under sitecorePath="/sitecore/content/Sites/Main", but it isn't clear how I can make this work.
The only other posts that cite this error are below:
https://www.linkedin.com/pulse/jss-layout-services-troubleshooting-arvind-gehlot
https://hishaamn.wordpress.com/2021/06/18/sitecore-jss-sxa-application-not-found/
One of these mentioned this:
The Root start item (in your site config patch file) should be a descendant of an App item
Clearly, branch templates are not a descendant of an App item, but could we somehow make them be a descendant of an App item? Or is there another way to get this working?
| |
You could try and set WEBSITE_DISABLE_OVERLAPPED_RECYCLING=1
Overlapped recycling makes it so that before the current instance on an app is shut down, a new instance starts. It can in some cases cause file locking issues, in which case you can try turning it off:
For reference - https://github.com/projectkudu/kudu/wiki/Configurable-settings#disable-overlapped-recycling
Also see this issue on github - https://github.com/docker-solr/docker-solr/issues/347
| Issue when populating managed schema for our Sitecore Solr index
I'm am getting an issue when trying to rebuild the Sitecore Solr index by clicking on populate managed schema and rebuild.
sitecore_core_index is already locked. The most likely cause is another Solr server
Our Solr is deployed on Azure app service. We are using the same Solr endpoints/URLs for multisite.
Job started: Index_Update_Collection=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="error">
<lst name="metadata">
<str name="error-class">org.apache.solr.core.SolrCoreInitializationException</str>
<str name="root-error-class">org.apache.lucene.store.LockObtainFailedException</str>
</lst>
<str name="msg">SolrCore 'sitecore_core_index' is not available due to init failure: Index dir 'C:\home\site\wwwroot\server\solr\sitecore_core_index\data\index/' of core 'sitecore_core_index' is already locked. The most likely cause is another Solr server (or another solr core in this server) also configured to use this directory; other possible causes may be specific to lockType: native</str>
<str name="trace">org.apache.solr.core.SolrCoreInitializationException: SolrCore 'sitecore_core_index' is not available due to init failure: Index dir 'C:\home\site\wwwroot\server\solr\sitecore_core_index\data\index/' of core 'sitecore_core_index' is already locked. The most likely cause is another Solr server (or another solr core in this server) also configured to use this directory; other possible causes may be specific to lockType: native
at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:1781)
at org.apache.solr.servlet.HttpSolrCall.init(HttpSolrCall.java:253)
at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:538)
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:750)
Caused by: org.apache.solr.common.SolrException: Index dir
| |
It is possible that your source file uses an encoding different from UTF8 or your system default. Please double check the encoding of the file your are uploading into the Media Library and then use the same encoding in PowerShell script. If your CSV file was created in Excel, most likely you will need Windows-1252 encoding.
I have tested your code with a CSV file similar to this:
Column1,Column2
äää,äää
üüü,üüü
On my machine, a file in ANSI encoding works well with the line
[System.Text.Encoding]::Default.GetString($contents),
UTF-8 file works with the line [System.Text.Encoding]::UTF8.GetString($contents), and Excel-generated CSV file in Windows-1252 encoding works only with the line [System.Text.Encoding]::GetEncoding(1252).GetString($contents). All other combinations produce an incorrect result.
For reference, here is the full script that I used:
function ReadCSV($media)
{
[System.IO.Stream]$body = $media.Fields["Blob"].GetBlobStream()
try
{
$contents = New-Object byte[] $body.Length
$body.Read($contents, 0, $body.Length) | Out-Null
}
finally
{
$body.Close()
}
return $contents;
}
function ConvertToDynamicObject($contents)
{
return $csv = [System.Text.Encoding]::GetEncoding(1252).GetString($contents) | ConvertFrom-Csv -Delimiter ","
}
function ImportItem($csv)
{
foreach ($row in $csv)
{
Write-Host $row.Column1, $row.Column2
$item = Get-Item "master:/content/home"
$newItem = New-Item -Parent $item -Name $row.Column1 -ItemType "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}"
$newItem.Editing.BeginEdit()
$newItem["Title"] = $row.Column2
$newItem.Editing.EndEdit()
}
}
$csvMediaItem = Get-Item -Path "master:/sitecore/media library/Files/test-excel"
$csvContent = ReadCSV($csvMediaItem)
$csvDynamicObject = ConvertToDynamicObject($csvContent)
ImportItem($csvDynamicObject)
This is the result I got with the above script and sample CSV:
| PowerShell special characters encoding
I've built a PS script to create and populate items from a CSV file. The issue is that chars like ä, ü, ö are replaced with � in the field values. I've changed the encoding from ConvertToDynamicObject() function from 'Default' to 'UTF8', without luck.
The function to read the CSV:
function ReadCSV($media)
{
# get stream and save content to variable $content
[System.IO.Stream]$body = $media.Fields["Blob"].GetBlobStream()
try
{
$contents = New-Object byte[] $body.Length
$body.Read($contents, 0, $body.Length) | Out-Null
}
finally
{
$body.Close()
}
return $contents;
}
Then I convert the byte[] to a Dynamic object:
function ConvertToDynamicObject($contents)
{
# convert to dynamic object
return $csv = [System.Text.Encoding]::Default.GetString($contents) | ConvertFrom-Csv -Delimiter ","
}
Then process the data:
function ImportItem($csv)
{
foreach ($row in $csv)
{
# ...
}
}
| |
This Sitecore docs page will probably be the most helpful to you:
https://doc.sitecore.com/xp/en/developers/hd/201/sitecore-headless-development/working-with-placeholders-in-a-jss-next-js-app.html
Otherwise, here is an example of a simple placeholder-style component in TypeScript.
Not much setup is required on the Sitecore side for very basic placeholder components. In your wrapper rendering:
/sitecore/layout/Renderings/Feature/MyWrapperComponent, add a placeholder key in the Layout Service Placeholders field that defines which renderings can be added to your placeholder.
Here is your wrapper component:
MyWrapperComponent.tsx
import { Placeholder } from '@sitecore-jss/sitecore-jss-nextjs';
...
return(
<>
<Placeholder name="myWrapperComponentItems" rendering={props.rendering} myArbitaryProp={true} />
</>
);
...
MyWrapperComponentItem.tsx
...
type MyWrapperComponentItemProps = ComponentProps & MyWrapperComponentItem & {
fields: {
...
};
myArbitaryProp: boolean;
};
const MyWrapperComponentItem = (props: MyWrapperComponentItemProps): JSX.Element => {
const { fields } = props;
// Can use myArbitaryProp in here if desired
return (
<>
<RichText field={fields.myField} />
</>
);
};
...
After adding the components to the page, the layout service should return something like this:
{
"uid": "xxxxxxx-xxxxxx-xxxx-xxxx-xxxxxx",
"componentName": "MyWrapperComponent",
"dataSource": "",
"params": {},
"placeholders": {
"myWrapperComponentItems": [
{
"uid": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxx",
"componentName": "MyWrapperComponentItem",
"dataSource": "{xxxxxxxx-xxxxx-xxxx-xxxx-xxxxxxx}",
"params": {},
"fields": {
...
}
},
{
"uid": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxx",
"componentName": "MyWrapperComponentItem",
"dataSource": "{xxxxxxxx-xxxxx-xxxx-xxxx-xxxxxxx}",
"params": {},
"fields": {
...
}
}
]
}
}
| How do you create Components with children like Tabs, Carousels, Search Results or List of Cards?
I am just transitioning from Sitecore MVC to SitecoreNextJs. I have been able to create simple components fairly easily, but haven't been able to create components with children, like tabs, carousels, search results or a list of cards.
I referred to this article with placeholders:
https://doc.sitecore.com/xp/en/developers/hd/200/sitecore-headless-development/walkthrough--creating-a-new-component-in-a-jss-next-js-app-using-the-sitecore-first-development-workflow.html
but the code throws errors (since I am using TypeScript). Could anyone please point me to some documentation/examples?
Thanks!
| |
Forgot password is in sitecore/login/default.aspx file in section
<div id="passwordRecovery" runat="server" style="display: none">
Login is inside Identity Server service by default, in file
sitecore\Sitecore.Plugin.IdentityServer\Views\Account\Login.cshtml
| Where are Login, Forgot password pages located in instance - 10.2
I need to customize these default CMS pages, by adding some HTML attributes for the form fields.
Login
Forgot Password
Please let me know, where they reside.
I tried /sitecore/login/default.aspx, /sitecore/admin/login.aspx but neither are correct.
| |
Looks like your hostname is not having your domain name.
Try adding the below patch config to your app_config/include folder and make sure this patch file is named such that it sits at the bottom.
Update the fields in upper case with Relevant information.
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<!-- CUSTOM SITES -->
<sites>
<site name="YOURSITENAME" patch:before="site[@name='modules_website']"
hostName="YOURDOMAINNAME|localhost"
targetHostName="YOURDOMAINNAME"
scheme="https"
port="443"
virtualFolder="/"
physicalFolder="/"
rootPath="/sitecore/content/YOURSITENAME"
startItem="/Home" database="web"
dictionaryPath="/sitecore/content/Dictionary"
dictionaryAutoCreate="false"
domain="extranet"
allowDebug="true"
cacheHtml="true"
htmlCacheSize="100MB"
registryCacheSize="0"
viewStateCacheSize="0"
xslCacheSize="5MB"
filteredItemsCacheSize="2MB"
enablePreview="true"
enableWebEdit="true"
enableDebugger="false"
enableWorkflow="true"
disableBrowserCaching="false"
disableClientData="false"
disableXmlControls="true"
notFoundItem="/sitecore/content/home/system/Page not found"
itemwebapi.mode="Off"
itemwebapi.access="ReadOnly"
itemwebapi.allowanonymousaccess="false"
robotsTxt="/robots.txt"/>
</sites>
</sitecore>
</configuration>
Hope This helps.
| How should I remove the default home item & website name from the URL?
Recently I have upgraded our site from v10.0.2 to v10.0.3 using XM topology. After upgrade I have rebuilt the indexes / link databases as well.
But after upgrading sitecore is generating URL like below.
https://{domain}/websitename/home/pathofitem - from this pattern how I can remove websitename/home from the URL?
SiteDefinition
<site patch:before="*[@name='website']" name="websitename" enableTracking="true" hostName="localhost|*.xyz.com" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content/websitename"
startItem="/Home" database="web" domain="extranet" loginPage="/login" allowDebug="true" cacheHtml="true" htmlCacheSize="50MB" registryCacheSize="0"
viewStateCacheSize="0" xslCacheSize="25MB" filteredItemsCacheSize="10MB" enablePreview="true" enableWebEdit="true" enableDebugger="true"
disableClientData="false" cacheRenderingParameters="true" renderingParametersCacheSize="10MB" />
| |
IFrame source will be blocked by Content Security Policy. Update you CM web.config Content-Security-Policy by adding desired Url. See below for tested example on Sitecore 10.0.1:
<location path="sitecore">
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Content-Type-Options" />
<remove name="X-XSS-Protection" />
<remove name="Content-Security-Policy" />
<add name="X-XSS-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff " />
<add name="Content-Security-Policy" value="default-src 'self' https://tools.eurolandir.com 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' 'unsafe-inline' https://fonts.gstatic.com; upgrade-insecure-requests; block-all-mixed-content;" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
| The rich text block iframe in Editor mode
I have added this iframe in Sitecore RTE field
<iframe class="EurolandTool" src="https://tools.eurolandir.com/tools/FinCalendar2/?companycode=ae-nbad&v=ae-nbad_redesign2017&lang=en-gb" width="100%" height="500" scrolling="no" frameborder="0"></iframe>
but it is blocked in editor mode. Do you have an idea about the problem?
| |
I found the answer, the audience url is incorrect in sitecore documentation.
it is should be https://api.sitecorecloud.io and it's worked for me.
Sharing here for reference.
| Experience Edge XM OAuth Credentials "Service not enabled within domain"
I am trying to generate JWT token by using the oAuh client credentials XM cloud. referring JWT for Experience Edge link.
getting Service not enabled within domain: https://auth.sitecorecloud.io error with 403 forbidden status code.
.
Can someone please help me, how can I enable the service domain?
Thanks
| |
You can just join:
date + only not hyphens pattern:
^(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[-/.]((19|20)[0-9][0-9])[^\-]+$
with
only not hyphens pattern:
(^[^\-]+$)
using or |
Final regex is:
(^(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[-/.]((19|20)[0-9][0-9])[^\-]+$)|(^[^\-]+$)
Btw I changed the order of date and year in your pattern so it matches now 01-01-2023 instead of 2023-01-01 like in your regex.
| Regex validator on display name for hyphen(-) value
I need to create a regex field validator on display name such that it should not have hyphen(-) unless if there is any date in the name.
Display Name
Validation Error/ Allowed
This is a Display Name
Allowed
This is a-Display Name
Validation error. There is a "-" in between a and Display
01-01-2023 This is Display Name
Allowed
01-01-2023 This is Display-Name
Validation Error. There is a "-" in between Display and Name
This regex validates DATE: "^((19 | 20)[0-9][0-9])[- /.](0[1 - 9] | 1[012])[- /.](0[1 - 9] |[12][0 - 9] | 3[01])"
This regex validates "-"(HYPHEN): "[-]"
I don't know how to merge both and make my use cases work. Any experts here? Thanks in advance.
| |
This question is very close to being opinion based, but I think we can answer the differences more factually here.
tl/dr: No, Unicorn is not obsolete with Sitecore 10. Unicorn is not compatible with XM Cloud.
Unicorn and SCS use very similar yaml file formats, the SCS yaml file is based on the original Rainbow yaml serializer that Unicorn uses, although it is not the same code.
The biggest difference is how the tool runs. Unicorn runs as part of the Sitecore application instance. The configuration is all based on include files and those need to be deployed with your application. Your yaml files need to be accessible by the CM application too.
SCS runs as part of the Sitecore CLI dotnet tool. This can run from anywhere that can run a PowerShell command. The config and yaml files need to be accessible to the CLI, they are not deployed with the application.
Because of that difference, your only option for XM Cloud is to use SCS. For Sitecore 10+, both tools are valid. Unicorn has some more advanced configuration available for working out the items to serialize/config inheritance etc... The CLI has somethings available that are not in Unicorn - Creating IAR files from your serialized items for example.
If you are starting a new project, you should look at your requirements for serialization and select the best tool for your project. Unicorn is open source, there is a very active community around it and if you find a bug, I'm sure Mark will be more than happy to accept a PR to fix it for everyone. SCS is not open source but comes with support from Sitecore. You have to decide which is for you, unless as I mentioned above, you are on XM Cloud. Then your choice is made.
| Is Unicorn obsolete with Sitecore 10?
As far as I understand, Unicorn still works with Sitecore 10.x and I understand that Sitecore 10 introduced a new Serialization format.
So... does the new Serialization system of Sitecore 10 make Unicorn obsolete, or is there still some functionality that Unicorn has which is not yet covered by Sitecore 10?
I understand that Sitecore 10 serialization is controlled by the CLI, so there would not be an equivalent to the unicorn sync page, so from a UI perspective, Sitecore 10 misses that feature.
| |
It's hard to trip down memory lane, as it's been a while.
You can try out following code to get the personalized datasource.
public static List<Item> GetPersonalizationDataSourceItems(this Item i)
{
List<Item> list = new List<Item>();
foreach (RenderingReference reference in i.GetRenderingReferences())
{
list.AddRange(reference.GetPersonalizationDataSourceItem());
}
return list;
}
private static List<Item> GetPersonalizationDataSourceItem(this RenderingReference reference)
{
List<Item> list = new List<Item>();
if (reference != null && reference.Settings.Rules != null && reference.Settings.Rules.Count > 0)
{
foreach (var r in reference.Settings.Rules.Rules)
{
foreach (var a in r.Actions)
{
var setDataSourceAction = a as Sitecore.Rules.ConditionalRenderings.SetDataSourceAction<Sitecore.Rules.ConditionalRenderings.ConditionalRenderingsRuleContext>;
if (setDataSourceAction != null)
{
Item dataSourceItem = GetDataSourceItem(setDataSourceAction.DataSource, reference.Database);
if (dataSourceItem != null)
{
list.Add(dataSourceItem);
}
}
}
}
}
return list;
}
Referance link: https://horizontal.blog/2015/09/08/programmatically-get-personalization-datasource-items-of-a-sitecore-item/
Hope it helps!
| How can I get the datasource of a personalized sublayout (webforms)?
I'm working on enabling sublayout caching for personalized sublayouts.
public class ContextCacheableSublayout : Sublayout
{
public override string GetCacheKey()
{
var cacheKey = base.GetCacheKey();
cacheKey = string.Concat(cacheKey, GetCustomCacheKeyPart());
return cacheKey;
}
private string GetCustomCacheKeyPart()
{
//// GET DATASOURCE WITH PERSONALIZATION
}
}
Basically I just need to generate a cache key based on the correct datasource given the personalization rules. I have the Sublayout already, which has this.Datasource. But how do I make sure to get the current personalized datasource?
I'm following this post as a reference but it pertains to MVC, and I'm not sure how to do the same things with webforms
| |
The parameters that are passed in are used to build a predicate and fired off for search results from the Search API. The OOTB parameters allow for very powerful and fast queries for data but are limiting by a key factor. It does not support filter by date and sorting, so you cannot control the order in which your results are returned. In a recent implementation, we had to add date filter fromdate,todate and sorting to allow us to retrieve data sorted by date in given date range.
Most standard sorting will work, but it likely won't give you the desired result if you're trying to sort something like a date. To do this, you will need to convert your date field to a string-sortable friendly value. My recommendation is to create a computed index for your date fields to store the value in ticks.
You can find the full implementation for the ExtendedSearchQuery in a gist here: ExtendedSitecoreQuery.
Hopefully, this helps.
| Get Sitecore Items based on the dates by using graphql
I have a requirement to fetch the news items in between the fromDate and toDate. fromDate and toDate need to pass as a parameter so i am unable to forming the query. for your reference please find the below screenshot.
| |
This appears to be the same as an issue I bumped into when upgrading the CLI/Sitecore Management Service 5.1.25 in a solution using Sitecore Headless Rendering 20.0.0 on XP 10.2
There are a few assemblies that crossover between the two asset images (e.g. Sitecore.Services.GraphQL.dll). Applying the asset image to the CM for Sitecore Management Service 5.1.25 before the asset image for Sitecore Headless Rendering 20.0.0, results in the latter's assemblies being used. However the assemblies from Sitecore Headless Rendering 20.0.0 do not support the GQL headers required to support the versionComparingEnabled flag used in CLI v5.1.25.
Headless services 20.0.2 was released to support this and appropriate images have been pushed to the Sitecore Container Registry. Assuming you are currently using Sitecore Headless Rendering 20.0.0 (or 20.0.1), then upgrading your solution to use the 20.0.2 tags should resolve this issue. The release notes for 20.0.2 can be found here:
https://dev.sitecore.net/Downloads/Sitecore%20Headless%20Rendering/20x/Sitecore%20Headless%20Rendering%202002/Release%20Notes
Unfortunately this incompatibility is not currently noted in the CLI 5.x upgrade documentation.
| CLI Error: "The Sitecore Management Service version of the environment this Sitecore CLI operates with is outdated"
There is Sitecore 10.2 solution running with CLI tool v4.2. In order to upgrade to CLI v5.1 the following steps were done:
In sitecore.json all the plugin versions have been updated:
"plugins": [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
],
In the .env file, the MANAGEMENT_SERVICES_IMAGE version has been updated:
MANAGEMENT_SERVICES_IMAGE=scr.sitecore.com/sxp/modules/sitecore-management-services-xm1-assets:5.1-1809
Containers have been rebuilt with --no-cache option. But there is still a version conflict. The CLI error:
The Sitecore Management Service version of the environment this Sitecore CLI operates with is outdated, please update the Sitecore Management Service to version 5.1.25.
Locally, it can be mitigated via unrecommended setting in sitecore.json, but the error still appears on build agents where we build/install serialization packages:
"settings": {
"versionComparingEnabled": false
}
What causes this version conflict?
| |
As per the Sitecore documentation, the AuthenticationManager.Logout() method does everything automatically.
When a user signs out from an external identity provider, Sitecore Identity redirects the user to the logout page of this identity provider, and then back to Sitecore. A full sign out from both Sitecore and the underlying identity provider usually cannot happen with a single request.
However, Sitecore Identity handles everything automatically when you use the AuthenticationManager.Logout() method.
You can refer to the document for more details.
https://doc.sitecore.com/xp/en/developers/102/sitecore-experience-manager/understanding-sitecore-authentication-behavior-changes.html
| Correct way to Sign out a user programmatically
I'm working on an application which has custom admin pages in CMS and also the front-end website.
Both these have the Sign-out feature and this is the method being used to sign out the user.
AuthenticationManager.Logout();
This works, but is there anything else that needs to be done like deleting cookies etc.
Using Sitecore 10.2
| |
It is not necessary, but if you are creating a user by passing a domain that doesn't exists in the domains.config then the user will be created but the domain entry for this will remain blank.
I have created a user called myuser1 by passing a hardcoded domain called 'rbtest' that is not listed in domains.config. So when I see the user in the user manager then it shows but as a blank entry in the domain column.
On the other way when I create a user by passing the domain that exists in domains.config called myuser with the domain called sitecore, then it shows the domain entry like this.
So note that the domain column on UI is fulfilled only if an existing domain is specified.
Hope this makes sense.
| Is adding a Domain in config necessary while creating users programmatically
I have not added my custom domain in Domains.config. I'm able to create the users programmatically by passing the domain name as a hardcoded string to the method.
The users are listed in User Manager.
So, is it mandatory to have the custom domain declaration in Domains.config.
Using Sitecore 10.2
| |
You can only see stats.aspx (and other Sitecore admin pages) on CM server.
Stats are collected according to Sitecore.Context.Site, so when you see only shell page in stats page, that means that since last restart of your CM server (or since the last time one clicked Reset on stats page), the only visited site on CM server was Sitecore backend.
You will not see any stats from CD servers.
So unless you're using Standalone setup, you won't really see any "live" starts from your client facing websites.
| Stats.aspx page in Sitecore
I wanted to understand how does stats.aspx page work in Sitecore? is there any specific setting that needs to be done to get Site specific renderings? Sometimes when I visit the Admin page - stats.aspx I can see my Website being listed there and sometimes I just see "shell ". How can I get my website tab listed there?
Thanks in advance!
| |
Here is a basic example at how you can take a known root ID of "Redirects" and output all of the mappings.
$redirectsRootId = "{CE4886A6-0372-42FB-B27E-B1E417A4A2F2}"
$redirectMaps = Get-ChildItem -Path "master:" -ID $redirectsRootId | Where-Object { $_.TemplateID -eq "{F4FB6125-F113-4373-8AA2-4648C2C1960E}" }
$records = [System.Collections.ArrayList]@()
foreach($redirectMap in $redirectMaps) {
$nameValues = [System.Web.HttpUtility]::ParseQueryString($redirectMap.UrlMapping)
foreach($key in $nameValues.AllKeys) {
$record = [PSCustomObject]@{
"Old" = $key
"New" = $nameValues[$key]
}
$records.Add($record) > $null
}
}
$records | Show-ListView
References
NameValueList
| Export all Redirect Maps
Is there a way to export all redirect maps via a PowerShell script or a simple GUI in Sitecore that I am missing? I want a list of them all - don't care about the formatting as long as I can make sense of it.
I have 3 Redirect Map Groupings and redirects under those. I simply would like to export everything under Sitecore's main Redirects group.
The setup is as described here - https://doc.sitecore.com/xp/en/users/sxa/102/sitecore-experience-accelerator/map-a-url-redirect.html
Is this possible without a heavy lift, installing something, and/or going one by one copying out the raw values for each?
| |
When you want to override any Sitecore dialog, you can put your own version of it in sitecore\shell\override directory.
That's explained here:
https://doc.sitecore.com/xp/en/SdnArchive/Scrapbook/Customize%20an%20XML%20Control.html
SXA works in the same way. If you want to disable their version of dialog, delete file:
sitecore\shell\Override\Applications\Dialogs\SelectRenderingDatasource\SelectRenderingDatasource.xml
| Disabling SXA rendering dialogs in Experience editor
We added SXA module into our newly upgraded Sitecore 10.2 solution. However we found out SXA doesn't work well with our non-SXA solution side by side, especially in the Experience Editor. For example, the new "Select a Rendering" dialog and editor needs to select the right datasource template instead of the datasource created by using the defined template automatically.
We don't want to uninstall SXA, but can we make the experience editor use those default rendering dialogs instead of SXA's?
| |
For adding a frame-ancestor header only for a specific site in non SXA website you have to do customization, SXA have this feature. You can take reference from below link in non SXA website.
https://www.sitecorenutsbolts.net/2018/07/27/Sitecore-SXA-Using-HTTP-Headers-to-Secure-Your-Site/
Hope this helps you.
| Adding a frame-ancestor header only for a specific site
Is it possible to add a frame-ancestor header only for a specific site in our multisite Sitecore environment? What I saw were articles suggesting to add the header in the web.config but that would add the header to all sites then, wouldn't it? I also saw articles that has a module for it but it's only for SXA (our site isn't built on SXA).
I can attempt to override the XFrameOptionsHeaderModule but that doesn't seem like good practice.
| |
If you are getting slow performance on your Experience Editor locally, you are probably running out of resources in your docker container. By default, docker gives your container 1gb RAM and shares the host CPU. On your CM container, the 1gb limit is easily hit.
You can give it more by modifying your docker-compose-override.yml file. Find your cm container definition and add the following lines:
cm:
image: ${REGISTRY}${COMPOSE_PROJECT_NAME}-xmcloud-cm:${VERSION:-latest}
build:
context: ./docker/build/cm
args:
PARENT_IMAGE: ${SITECORE_DOCKER_REGISTRY}sitecore-xmcloud-cm:${SITECORE_VERSION}
TOOLS_IMAGE: ${TOOLS_IMAGE}
# **** ADD THESE LINES ****
deploy:
resources:
limits:
cpus: 1.0 # <--- gives it a dedicated core
memory: 6GB # <--- set this to a reasonable limit based on your machine specs.
# **** ADD THESE LINES ****
volumes:
- ${LOCAL_DEPLOY_PATH}\platform:C:\deploy
- ${LOCAL_DATA_PATH}\cm:C:\inetpub\wwwroot\App_Data\logs
- ${HOST_LICENSE_FOLDER}:c:\license
environment:
SITECORE_LICENSE_LOCATION: c:\license\license.xml
RENDERING_HOST_INTERNAL_URI: "http://rendering:3000"
JSS_DEPLOYMENT_SECRET_xmcloudpreview: ${JSS_DEPLOYMENT_SECRET_xmcloudpreview}
SITECORE_JSS_EDITING_SECRET: ${JSS_EDITING_SECRET}
SITECORE_EDITING_HOST_PUBLIC_HOST: "${RENDERING_HOST}"
SITECORE_Pages_Client_Host: ${SITECORE_Pages_Client_Host}
SITECORE_Pages_CORS_Allowed_Origins: ${SITECORE_Pages_CORS_Allowed_Origins}
# ADD THIS LINE
SITECORE_GRAPHQL_CORS: ${SITECORE_GRAPHQL_CORS}
# Development Environment Optimizations
SITECORE_DEVELOPMENT_PATCHES: DevEnvOn,CustomErrorsOff,DebugOn,DiagnosticsOff,InitMessagesOff
Sitecore_AppSettings_exmEnabled:define: "no" # remove to turn on EXM
entrypoint: powershell -Command "& C:/tools/entrypoints/iis/Development.ps1"
This should make your CE and EE run better locally. Also, you can now use Pages to edit your content locally. To do this you need to:
Visit https://pages.sitecorecloud.io in your browser
Open the dev tools and add a new key to the local storage for that site
Key Sitecore.Pages.LocalXmCloudUrl
Value: https://xmcloudcm.localhost/
Reload the pages site and you should see your local site editable. If you get CORS issues, make sure these values are set in your .env file:
SITECORE_Pages_Client_Host=https://pages.sitecorecloud.io
SITECORE_Pages_CORS_Allowed_Origins=pages.sitecorecloud.io
SITECORE_GRAPHQL_CORS=*.sitecorecloud.io
Documentation for all this is here: https://doc.sitecore.com/xmc/en/developers/xm-cloud/connect-sitecore-pages-to-your-local-xm-cloud-instance.html
| Sitecore XM Cloud local instance Experience Editor "The operation has timed out"
Has anyone else been experiencing this problem when trying to open the Experience Editor for a page or a partial view when performing local development for Sitecore XM Cloud? I am using the template https://github.com/sitecorelabs/xmcloud-foundation-head
Sometimes after a refresh the Experience Editor appears and works fine. Other times it shows that message.
| |
You have to use Sitecore.Client dll reference in your project, after that you will be able to access Sitecore.Shell.Applications.ContentEditor.Pipelines.GetContentEditorFields.GetFields
Below is the pipeline processor for this
<processor type="Sitecore.Shell.Applications.ContentEditor.Pipelines.
GetContentEditorFields.GetFields, Sitecore.Client" >
</processor>
</getContentEditorFields>```
Hope this helps.
| Conditionally Hide fields from Content Editor
In one of my projects in Sitecore 10.2, I am using one base template in other child templates. My requirement is that I want to hide some base template fields in some child templates.
For that, I am referring
https://andrey-vinda.tech.blog/2017/10/30/sitecore-hide-fields-from-content-editor/.
In the above example, we have to inherit Sitecore.Shell.Applications.ContentEditor.Pipelines.GetContentEditorFields.GetFields
But I am not able to access it.
Any idea how we can get this namespace in Sitecore 10.2 Version?
| |
What you can do is in case of removing this, you should hide the checkbox from the xml that Sitecore uses to render the popup.
You can find this in Publish.xml file under the below location.
\wwwroot\<your-website-root>\sitecore\shell\Applications\Dialogs\Publish
And you should use Visible="false" to hide the check box that you want. For example, I am using it to hide Publish related items.
So the code will be like this.
<Checkbox ID="PublishRelatedItems" Header="Publish related items" Visible="false"/>
And there is also an information icon that you should hide like this.
<div class="publish-wizard-tooltip" >
<ThemedImage Src="office/16x16/information.png" Align="Center" Visible="false" />
<Literal class="publish-wizard-tooltiptext" Text='${Translate.Text(Texts.PublishesAllReferencesToTheItemThisMayIncreaseTheTimeItTakesToPublish)}' />
</div>
Now the publish wizard will look like this.
Hope this helps.
| How to Hide Publishing wizard Options
In one of my project I have a requirement that I want to hide out of the box publishing wizard feature. I.e. Publish Related Items.
| |
This is a known bug in JSS 21 and has been fixed in JSS 21.0.5.
The bug was that all dynamic placeholder keys must be called container-{*} - this was hard coded into the PlaceholderCommon.tsx file in JSS that resolves the dynamic placeholder key with the layout service JSON coming from the GraphQL call. This is why the out of the box components like the Container work ok.
Here is a link to the PR that fixed the issue: https://github.com/Sitecore/jss/pull/1278
To make sure that you don't get this problem, update your package.json file to use JSS 21.0.5 for the following packages:
"@sitecore-jss/sitecore-jss-nextjs": "^21.0.5",
"@sitecore-jss/sitecore-jss-cli": "^21.0.5",
Then re-install your npm packages and you should be able to create your custom placeholder keys.
| XM Cloud component with dynamic placeholder
I wanted to try and create a custom container component such that it can be placed many times on the page and I can add components to it. I was having a problem at the time of seeing it in Experience Editor. Currently using the https://github.com/sitecorelabs/xmcloud-foundation-head template.
I follow the approach suggested here in order to create a custom container component in order for it to have variants. Why aren't SXA rendering variants available for the default "Page Structure" renderings?. What I did was clone the /sitecore/layout/Renderings/Feature/JSS Experience Accelerator/Page Content/PageContent component using the script.
The component has in the Experience Accelerator section, in the Other properties field, the value of IsRenderingsWithDynamicPlaceholders set to true. In the Layout Service section, in the Layout Service Placeholder, I have selected the newly created placeholder settings item I mention below.
I created a placeholder settings using /sitecore/templates/Foundation/JSS Experience Accelerator/Placeholder Settings/Placeholder. The placeholder key is custom-container-{*}.
I added the Variant and Default variant definition item in /sitecore/content/mySite/Presentation/Headless Variants/CustomContainer. Also made the rendering available in the Experience Editor.
Finally I implemented the component view. I used as base the https://github.com/sitecorelabs/xmcloud-foundation-head/blob/main/src/sxastarter/src/components/Container.tsx.
export const Default = (props: ComponentProps): JSX.Element => {
const phKey = `custom-container-${props.params.DynamicPlaceholderId}`;
return(
<div className="custom-wrapper">
<Placeholder name={phKey} rendering={props.rendering} />
</div>
);
}
I try to add one to Experience Editor and it successfully renders. However if I close it and then open it again, I get the error A rendering error occurred: Cannot read properties of undefined (reading 'attributes').. Inspecting the console I also found this warning Placeholder 'custom-container-1' was not found in the current rendering data.
I am currently struggling to solve this issue and am not sure of the recommended practice for this.
NOTE. If applying the suggested fix of updating the JSS in package.json, and get errors like File '/src/sxastarter/node_modules/@types/react/index.d.ts' is not a module, node_modules/@sitecore-jss/sitecore-jss-nextjs/types/index.d.ts' is not a module and Cannot find namespace 'JSX'. I got it fixed by closing the code editor and restarting the machine (just in case).
| |
To create user we followed below steps -
Go to Admin Panel and select Users
Click on Add User button
In the Details tab, provide the Username and Modules
In the User groups section - Click on Add to user group in the left hand side and select Superusers from popup.
Then in the Policy combination We selected any policy and select Add item, that's it, it will add superuser.
Save.
| How to create a superuser in Content Hub
I would like to create a superuser whose credentials will be used in the CMP connection string.
I see this error while trying to create a superuser. I tried all & any in the Policy combination section.
The operation causes a violation of a unique constraint on at least
one of the properties: for property define by..
Not sure of the version, but the Sitecore Connector for Content Hub being used in v4.0
UPDATE:
I was trying to create a user with name sitecorecmpsyncuser.
I tried sitecorecmpuser and it worked.
| |
You can authenticate by generating bearer token using postman as explain by Dan. http://www.dansolovay.com/2023/01/using-postman-to-authenticate-to-graphql.html
one more alternative is you can set requireAuthentication to false with the patch while using postman.
Go to file AppConfig\Sitecore\Services.GraphQL\Sitecore.Services.GraphQL.config
set <requireAuthentication>false</requireAuthentication>
More details: https://singhajit.com/how-to-integrate-graphql-with-sitecore-using-jss/
I tried an alternative approach and it works well.
Hope this helps!
| How do you authenticate the GraphQL endpoint in Postman?
I am getting 403 "Authentication required." when i hit the GraphQL query in Postman.
I am able to execute the same query in Sitecore GraphQL Playground.
In postman, i am passing the URL as https://{domain}/sitecore/api/graph/items/master?sc_apikey=key value
Also, Tried with using basic authentication with user name and password since Sitecore is using IDS for authentication.
How to make the authentication successful via postman?
| |
Access right applies on the item level, It will make the whole item editable or disabled. Access right does not work on the section level.
It looks like the current user you are logged in with does not have proper access writes to edit the item. You need to identify a role that is blocking the current user from read/write items. You need to use Access Viewer to review user/roles access rights and update roles according to to allow write access.
Go to launchpad and click on Access Viewer.
Select role/user from the top left Roles and Users selection box.
Select an item that is not accessible for the user/role.
It would come up with a right-side pane to show access permission specifically to the selected role/user.
In most cases sitecore\Author role is enough to allow content editing.
Hope it helps!
| Need to know which role to enable to get Indexing Section Enabled
I have a user that we dont want to give admin access to, but still want some of the functionallity from it. The indexing section to where you can boost values, rules and include in search is all greyed out with the priviledges they have know. Could someone point me to what role or security setting they need. Thank you.
| |
I agree with the approach shared by Sumit and Rishiraj, add on to that as you need only one rich text field to be allowed without HTML stripping you already
done mapFieldByFieldName. so I think it is something related to the configuration issue only. For better understanding and resolution, I did try with Sitecore 9.3 the following steps that will help you to investigate/fix an issue.
Patch file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultSolrIndexConfiguration>
<fieldReaders>
<mapFieldByFieldName hint="raw:AddFieldReaderByFieldName">
<fieldReader fieldName="Body Copy" fieldReaderType="Sitecore.ContentSearch.FieldReaders.DefaultFieldReader, Sitecore.ContentSearch" />
</mapFieldByFieldName>
</fieldReaders>
</defaultSolrIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
Validate the patch applied correctly using sitecore/admin/showconfig.aspx
Created 2 field Body Copy and DemoRichText2 in Sample Item template.
Index the home item only by selecting home item and then from ribbon go to Developer menu and then click on Re-index Tree.
Go to solr admin page and check for the home item.
Referance links:
https://learnsitecorebasics.wordpress.com/2016/05/30/sitecore-include-html-tags-in-indexes-for-rich-text-field/
Search HTML code in Content Editor
Hope it helps!
| Solr stripping out the HTML from Rich Text Field while indexing
I want to prevent stripping out the HTML from my one of the Rich Text Field.
I have the following field reader by field name in my index configuration file in place under the mapFieldByTypeName element.
It's still not keeping the inline HTML's for this field and it's stripping out. Is there any other settings i need to look into it?
<mapFieldByFieldName hint="raw:AddFieldReaderByFieldName">
<fieldReader fieldName="Body Copy" fieldReaderType="Sitecore.ContentSearch.FieldReaders.DefaultFieldReader, Sitecore.ContentSearch" />
</mapFieldByFieldName>
| |
That's absolutely normal that Content is returned as null from Solr (as _content field) in SearchResultItem.
Why? With Solr you can configure if a field should be:
only indexed - it means that you can search in content of the field
or indexed and stored - you can search in content + you can retrieve the full value of the field.
If you open conf\managed-schema file in your index folder in Solr and search for _content, you will see:
<field name="_content" type="text_general" indexed="true" stored="false"/>
That stored="false" part tells Solr that it should not waste space on the drive and in memory for storing the original value of the field.
Still you can execute queries on the field - that part will work as expected.
| Solr - The Content field in SearchResultItem is always null
Using Sitecore 10.2 with Solr 8.4.0.
I have Product pages which inherit from a template - Product Details.
This template has the following fields:
Title - Rich Text
Description - Rich Text
Category - Single Line
Tags - Treelist
I would like to perform a search for a term that can exist in Title or Description or Category.
In this Article which provides the basic steps to get started with Search, I see that it uses the Content field to search for the term.
But in my code, the Content property is null.
What should be configured & where, so that the Content property will include all text from Title & Description & Category
I have created a custom index and here is how the results are fetched.
public List<T> GetSearchResults<T>(string searchIndexName, string templateName, string searchTerm) where T : SearchResultItem
{
///get the index
ISearchIndex searchIndex = ContentSearchManager.GetIndex(searchIndexName);
///create a search context
using (IProviderSearchContext context = searchIndex.CreateSearchContext())
{
try
{
///build the query
var query = PredicateBuilder.True<T>();
if (!string.IsNullOrWhiteSpace(templateName))
{
query = query.And(x => x.TemplateName.Equals(templateName, StringComparison.InvariantCultureIgnoreCase));
}
if (!string.IsNullOrWhiteSpace(searchTerm))
{
query = query.And(x => x.Content.Contains(searchTerm));
}
/// get results from this index based on query
IQueryable<T> results = context.GetQueryable<T>().Where(query);
return results != null ? results.ToList() : null;
}
catch (Exception)
{
// ignored
}
return null;
}
}
custom index:
<?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 role:require="Standalone or ContentDelivery or ContentManagement" search:require="solr">
<contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes hint="list:AddIndex">
<index id="custom_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<param desc="name">$(id)</param>
<param desc="core">custom_index</param>
<param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
<configuration ref="contentSearch/indexConfigurations/defaultSolrIndexConfiguration" />
<strategies hint="list:AddStrategy">
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/manual" role:require="(ContentManagement and !Indexing) or (ContentDelivery and !Indexing)" />
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsyncSingleInstance" role:require="Standalone or (ContentManagement and Indexing) or (ContentDelivery and Indexing)" />
</strategies>
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>master</Database>
<Root>/sitecore/content/tenant/stratum/home/products</Root>
</crawler>
</locations>
<enableItemLanguageFallback>false</enableItemLanguageFallback>
<enableFieldLanguageFallback>false</enableFieldLanguageFallback>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
</configuration>
| |
As you wrote in your comment, Solr query generated for admin and non-admin users are the same.
I don't expect that you have any customizations for build in checks of security in Solr, so that would mean that for both admin and non-admin, Solr returns same results.
That means that some results are omitted on purpose by Sitecore, while converting Solr search results into what is shown in Content Editor.
The search logic happens in Sitecore.ContentSearch.Client.Pipelines.Search.SearchContentSearchIndex. From what I can see, the only reason why some search results are shown for Admin and hidden for non-admin users is if that non-admin user doesn't have Hidden items checked in VIEW ribbon:
You may want to check that one.
And if that's not the case, I suggest you decompile the class and replace original with your decompiled version and debug it (or debug Sitecore code if possible for you https://subbu.ca/blogs/debug-sitecore-dlls-made-easy-with-in-built-visual-studio-decompiler-and-symbol-generator/ )
| Sitecore Solr - Content Editor search returns no results but Experience editor and context search works fine
We are having the following issue. Please let me know if you have come across a similar issue or know of a potential solution.
In Sitecore Content Editor, all search queries works fine if logged in as admin.
For non Admin users, we have 3 different scenarios.
Experience Editor search works fine.
Context search in content editor from right side works fine.
Content Editor search on left side returns no results
We have content tree restriction for the non admin user but we are searching for terms where the user has access to the content. We have tried with very frequent used words and alphabets also, but no results show up on content editor search.
No errors logged in Sitecore log file, Sitecore search log and 'Solr' log files.
We are running our instance on Sitecore 8.2.
| |
You can extend search scope in Sitecore SXA with Solr. You can take reference from below URL for this
https://doc.sitecore.com/xp/en/users/sxa/19/sitecore-experience-accelerator/extend-search.html
Hope this helps you.
| Is it possible to generate Sitecore Search Scope across the entire tenant?
I have a requirement to display pages based on two different templates on two separate sites.
For example: Let's say I have one site called Site A and another site called Site B. In Site A, I have a template called Template A and in Site B, I have a template called Template B.
I need to display all the pages based on Template A and Template B in the 'Site A' directory page.
Thank you in advance.
| |
In Sitecore, the HTML cache is used to cache renderings/content (or pieces of the page), not the whole pages, and normally HTML cache is useful to improve the performance of the websites.
Cacheable - It basically says to Sitecore that this component should be cached - to use caching you need to enable this. This option should be enabled for the Vary by options to work. With only this setting enabled Sitecore will create a cache for the rendering and will use it to show same content every time that the component is used across all pages.
Vary by Query String - Selecting this Sitecore will cache different pieces for each query string that you have. So if you have a page that renders based on the query string for example the Search Page, can use that if you search text, the results page, and selected filters as a query string.
Reference link for brief details - https://konabos.com/blog/sitecore-10-1-cache-strategies
Hope it helps!
| When to enable Sitecore cache by query string
When should HTML Cache be enabled in Sitecore using "By Query String"? I believe one case would be search. Even in that case, on which component should it ideally be enabled?
| |
There is such a mechanism available where it will fall back to config files for values that are unset in the site settings item.
<sitecore>
<javaScriptServices>
<apps>
<app name="site"
sitecorePath="/sitecore/content/Tenant/Site"
serverSideRenderingEngine="http"
serverSideRenderingEngineEndpointUrl="$(env:EDITING_HOST)/api/editing/render"
serverSideRenderingEngineApplicationUrl="$(env:RENDERING_HOST)"
layoutServiceConfiguration="sxa-jss"
inherits="defaults" />
</apps>
</javaScriptServices>
</sitecore>
It is important to make sure the sitecorePath matches correctly.
| Is there a way to set fields on the Sitecore Headless / JSS Settings for the site via environment variables?
Prior to SXA-JSS you could define the JSS Site settings in the config and therefore be able to use environment variables for things like the serverSideRenderingEngineEndpointUrl.
Is there a mechanism to continue doing this now that this setting has moved into the /sitecore/content/Tenant/Site/Settings item?
| |
Sitecore is not capable of streaming media assets like video. When a user stores a video file in the Media Library, the browser must download the entire file before starting playback. Since even a small video file is several megabytes in size, this can destroy a visitor's page performance immediately. If there are a significant number of users on your site, a single Media Library video on your home page can take down your website entirely by overloading the Content Delivery server's ability to respond to requests.
Use a 3rd party video streaming provider like Brightcove, Vimeo, or even YouTube to host your videos and integrate them into Sitecore-hosted pages using their "embed" style players or JavaScript APIs. These 3rd party players can optimize the video's size base on the size of the player on page, and the user's available bandwidth, ensuring they get the highest-performance experience.
| How to Compress and Optimize the Video File Size
We are using SXA module in Sitecore 9.0.2. Our requirement is that while uploading a video file in to Sitecore CMS, how can we optimize or compress the size of video file. Please help on how to achieve this requirement.
Note: Content Hub is not supporting Sitecore 9.0.2 for SXA module:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0505663
| |
In the scenario you've described, the recommended approach would be to build the query predicate in the caller method and pass it as an argument to the Solr method (Approach 2). This approach allows you to build a more targeted and efficient query by only fetching the results that match the search criteria, rather than fetching all products and then filtering them in the caller method.
Building the query predicate in the caller method also makes it easier to add or modify search criteria and filters, as you can simply update the query logic without having to change the implementation of the Solr method.
With Approach 2, you can use a library like PredicateBuilder to construct complex query predicates that combine multiple search criteria and filters using logical operators such as AND and OR. This can help make the query code more readable and maintainable.
In addition, you can also consider using Solr's built-in search features, such as faceting, to further refine the search results based on facets such as color, brand, or price range. This can help users to filter and navigate the search results more easily.
Overall, Approach 2 provides a more flexible and scalable approach to implementing a search functionality in your application, while minimizing the amount of data that needs to be fetched and processed.
| Solr - Recommended way to search by filters
I'm trying to build a generic Search method GetSearchResults that would fetch results from Solr.
Sample use Case: Get a list of all products where the searchTerm can be in the Title OR Description field AND other facet filters like Color, brand etc.
What would be the recommended approach among these:
First get all products from Solr and then filter by criteria in the caller method.
Build the query predicate in the caller method & pass it as an argument to the Solr method.
If there is any other better approach, please let me know.
Approach 1: Get all products from Solr and then filter by criteria in the caller method.
public List<T> GetSearchResults<T>(string searchIndexName, List<string> templateNames, string languageIsoCode) where T : SearchResultItem
{
ISearchIndex searchIndex = ContentSearchManager.GetIndex(searchIndexName);
using (IProviderSearchContext context = searchIndex.CreateSearchContext())
{
var query = PredicateBuilder.True<T>();
if (templateNames != null && templateNames.Count > 0)
{
foreach(string templateName in templateNames)
{
query = query.Or(x => x.TemplateName.Equals(templateName, StringComparison.InvariantCultureIgnoreCase));
}
}
if (!string.IsNullOrWhiteSpace(languageIsoCode))
{
query = query.And(x => x.Language.Equals(languageIsoCode, StringComparison.InvariantCultureIgnoreCase));
}
IQueryable<T> results = context.GetQueryable<T>().Where(query);
return results != null ? results.ToList() : null;
}
}
public void CallerMethod(string searchTerm, List<KeyValuePair<string, string>> facets)
{
List<ProductSearchRelatedItem> results = GetSearchResults<ProductSearchRelatedItem >("custom_index", null, "en")
foreach(ProductSearchRelatedItem psri in results)
{
/// process the filtering logic here
}
}
Approach 2: Build the query predicate in the caller method & pass it as an argument to the Solr method.
public List<T> GetSearchResults<T>(string searchIndexName, Expression<Func<T, bool>> query) where T : SearchResultItem
{
ISearchIndex searchIndex = ContentSearchManager.GetIndex(searchIndexName);
using (IProviderSearchContext context = searchIndex.CreateSearchContext())
{
IQueryable<T> results = context.GetQueryable<T>().Where(query);
return results != null ? results.ToList() : null;
}
}
public void CallerMethod(string searchTerm, List<KeyValuePair<string, string>> facets)
{
var query = PredicateBuilder.True<T>();
/// build all the query AND/OR logic here
......
List<ProductSearchRelatedItem> results = GetSearchResults<ProductSearchRelatedItem >("custom_index", query)
}
| |
To get the URL of selected item in the multilist (reference filed) you can build up a query like below.
Here I'm using the default jss site with running a local docker/graphql instance.
query GetItemByItemID($itemId: String!){
item(path:$itemId){
... on StyleguideFieldUsageContentList{
name
path
sharedContentList{
targetItems{
... on StyleguideContentListItemTemplate{
url
displayName
textField{
value
}
}
}
}
}
}
}
Query Variables:
{"itemId":"{4394DB92-9283-5AC6-9E8C-5C60DC32A140}"}
GraphQL requires that you construct your queries in a way that only returns concrete data. Each field has to ultimately resolve to one or more scalars. That means you cannot just request a field that resolves to a type without also indicating which fields of that type you want to get back.
That's what the error message you received is telling you. you requested an ItemUrl!, but you didn't tell GraphQL at least one field to get back from that type.
@serhii has already given more details to fix it.
Hope it helps!
| Getting the url of the reference fields using Graph QL
I want to expose my Sitecore data to frontend using GraphQL edge queries. How do I get the url of the items selected in the multilist field? I tried using url keyword but getting the below error (see screenshot)
How can we achieve the same? Any help would be highly appreciated.
| |
It looks like a known issue and you can find the solution here in this link.
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1002165
The root cause of this issue is that all queries that start from the query: or local: prefix lead to generating the query to Solr. However, a request to the index during resolving the data source for the SXA component must not be sent.
You can find this in this article.
For Sitecore XP 9.0.2, download and install the patch compatible with the affected Sitecore XP and SXA product version found on this page:
https://github.com/SitecoreSupport/Sitecore.Support.368851.373937/releases
| Solr Error : ["undefined field query"]
We have upgraded our Sitecore instance from 8 to 9.0.2 version. In one of our component on datasource level we are using query like below.
query:./ancestor-or-self::*[@@templatename='Website']/Local Content/Header/Content Source
On front-end everything is working as expected, but when I saw search logs I am seeing below error multiple times.
ERROR Solr Error : ["undefined field query"] - Query attempted: [query:(.\/ancestor\-or\-self)].
If I am removing component from page then this error is not showing in search logs. Does anything needs to be updated in query syntax.
Please help me to resolve this error.
| |
Depending on a given field type you will have different editing options in Content.
From your screenshots I beleive that you are using a Simple Text field, if you would like to have a drop down list option to manage your content you can use a Drop-down Menu field type in your content item template. This will allow you to select a Sitecore item from a list.
Note that there are two types of drop-down menus that you can include in a content item template:
Drop Tree allows the user to select from a list with folders;
Drop List shows a simple list of items.
Read more here.
Please note that Horizon is no longer supported after XP 10.2 and is not included with XP 10.3, see here.
| In Pages editor, how can I add a droplist control so that I can add specific parameters for a Text Field?
I want to be able to add a droplist control (and have it appear) under the "Content" section when I select-to-edit a Text Field in the Pages editor.
My purpose for this is to add a way to specify which heading tag it should render whether its H1, H2, or H6.
I noticed that for an Image, it does have this thing like an image browser and I basically want the same but instead it would be a droplist.
Is there anyone here who can help me with this one?
| |
Speaking from experience on non-headless SXA: never change the default (feature or foundation) templates from SXA.
Create your own base template with your fields - add them to the same section if you want, that is possible. Add this base template to your site page template. Your editors will not notice the difference but this way you keep your changes nicely separated from the ootb templates.
And I'm no NextJS expert so if something is fishy there someone might elaborate on that - but normally you are completely free to create your head solution as you please.
| XM Cloud SXA add SEO fields to page template best practices
Based on a new requirements, we want to add a way for Content Editors to be able to specify the metadata SEO fields. I wanted to know if the following is a recommended way or if there is a better approach. We are using a solution based on https://github.com/sitecorelabs/xmcloud-foundation-head template.
I know there's this template /sitecore/templates/Feature/Experience Accelerator/SiteMetadata/_Seo Metadata that already has MetaKeywords and MetaDescription fields.
My idea was to add fields to this template and then add this to the base templates of the OOTB page template /sitecore/templates/Project/MySite/Page. This in order to add those fields to the content pages using this template (e.g. Home, About Us) and such.
Finally, I would modify the Next.js Layout.tsx component and update the Routefields default interface to include the new fields from SEO
interface RouteFields {
[key: string]: unknown;
Title?: Field;
//new SEO fields
}
const Layout = ({ layoutData }: LayoutProps): JSX.Element => {
const { route } = layoutData.sitecore;
const fields = route?.fields as RouteFields;
const isPageEditing = layoutData.sitecore.context.pageEditing;
const mainClassPageEditing = isPageEditing ? 'editing-mode' : 'prod-mode';
return (
<>
{/* <Scripts /> */}
<Head>
<title>{fields?.Title?.value?.toString() || 'Page'}</title>
<link rel="icon" href={`${publicUrl}/favicon.ico`} />
{/*Use new SEO fields here*/}
</Head>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.