output
stringlengths 34
25.7k
| instruction
stringlengths 81
31k
| input
stringclasses 1
value |
---|---|---|
Sitecore recommends a separate certificate for each instance to make it more secure and to limit the damage that could be done should a certificate be compromised.
That being said, I believe it is still valid to use a single certificate on multiple instances. I have seen one single wildcard certificate be used for all CM,CD, Proc, Rep and individual XConnect instances.
If you are experiencing issues with 403 forbidden, I recommend that you ensure each sitecore and Xconnect role has permission to access the private key for the certificates that it needs access too.
To do this, run MMC => navigate to correct certificate store. Right click => Manage private key.
Make sure for example the iis instance you are using has permission to access.
i.e. iis apppool\yourapp.cm
EDIT: apologies I didn't fully read your question regarding port numbers... I think you are over complicating the issue by using port numbers, I think you will come I to problems that way. Instead you could either use single wildcard certificate, or add multiple "subject alternative names" SANs to the same single certificate, and still use the one certificate.
| One Certificate for all instances in XP Scaled Installation - xDB Forbidden issue
I did an on-premise setup for Sitecore 9.3 XP Scaled environment. At the time of installation I created separate certificates using createcert.json file and common xconnect certificate thumbprint for all the instances.
Now going forward in production (which is also an On-Premise environment) we have to use one certificate provided by our IT team.
I did an installation with this single certificate thumbprint for all instances including xconnect. So here are my installation instances.
This certificate subject identifier is defined as uatcm.company.com
uatcm.company.com:433 (CM)
uatcm.company.com:1221 (xconnect collection)
uatcm.company.com:1222 (xconnect collection search)
uatcm.company.com:1223 (xconnect marketing automation)
uatcm.company.com:1224 (xconnect marketing automation report)
uatcm.company.com:1225 (processing)
uatcm.company.com:1226 (reporting)
uatcm.company.com:1227 (reference data)
uatcm.company.com:1228 (cortex processing)
uatcm.company.com:1229 (cortex reporting)
I have installed the CD instance and the 4 necessary certificates including thumbprint in connectionstring.config in CD machine and I am able to connect to these services with https.
My question is - is this a valid setup (using port numbers) ? If we need to create separate bindings so can we add these domains in one certificate and use it for all?
Right now I am getting FORBIDDEN 403 issue when I browse for Experience Analytics in my CM instance
| |
You can check a few things. Go to Visual Studio and right-click on view and select the properties tab.
Make sure the Build Action option for View is Content like in the below image.
Also Copy to Output Directory has 3 options, make sure to choose as per requirement.
| Sitecore: Foundation Project - Views Folder is not getting deployed during solution rebuild
During local solution rebuild or in Dev/QA deployments, one of my Foundation project's Views folder is not getting deployed to the webroot.
Note:
All the views folder from all the feature projects are getting deployed as expected.
None of the other foundation projects has views folder.
Version details:
Sitecore 10.1.2
Visual Studio 2019
Am I missing anything here?
Or, as per community blogs I see that the publishOptions has to be modified.
Can someone help me how do it allow my foundation views to be deployed.
Thanks in Advance!
| |
To change the optimization settings for a specific site:
In the Content Editor, navigate to sitecore/content/<Tenant>/<Site>/Presentation/Page Designs.
In the Asset Optimization section, in the Styles Optimizing Enabled and Scripts Optimizing Enabled fields, to override styles and scripts optimization settings, select:
Default – to inherit global settings
Yes – to always enable optimization for this site.
No – to always disable optimization for this site.
| Sitecore SXA not generating optimized.js file
Sitecore SXA has stopped generating the optimizedjs file when I upload the scriptminifiled.js
file
Any ideas what could be causing it to do so?
| |
Most probably your Sitecore.client.dll version is different in your solution or you don't have proper policies under - /sitecore/system/Settings/Security/Policies in core database -
Check if you have /sitecore/system/Settings/Security/Policies/Accounts/Can Browse Roles if not, please create a new one (you can duplicate /sitecore/system/Settings/Security/Policies/Experience Explorer/Can Explore so that you don't need to update any security on the item)
OR Try to replace your DLL with the vanilla Sitecore instance
The DLL version of Sitecore.client.dll you have added is higher version, then 10.1.0 so I am not sure if this is part of any patch or hotfix. So please make sure to check this before replacing the DLL.
| Access denied error when creating / edit user
When I try to add new user or edit existing user and assign some role by clicking 'Member Of' tab and then edit button, I am getting below error.
I am using Sitecore version 10.1.0 (rev. 005207)
Please help
| |
I had same issue while doing upgrade. Seems like indexes were not properly setup and hence even after rebuilding indexes could not see media files. After rectifying index issue (which I remember correctly custom index files) and successfully building index, could see media files.
| Why is Select Media Dialog Empty When Media Exists in Folder?
When we try to Browse to select an image for an image field, nothing appears in the Select Media dialog though we've confirmed there's content in the folder designated in the field's Source attribute.
(This happens for both the tree view and the list view.) If we then go through the Upload Media procedure, the upload completes (as verified by examining the designated folder) but the Select Media dialog remains empty, as does the affected image field after closing it.
Pertinent details: we are just completing an upgrade from Sitecore 8 to Sitecore 9.2. (I think it was behaving something like this in Sitecore 8, but can no longer confirm it.) We're using Lucene search, not Solr, at this time and have made a point of rebuilding the sitecore_master_index (along with a couple of others), knowing this can be a factor. It may also be worth noting that, in the pre-deployment environment I'm currently working on, the designated folder for this upload is very big - some few hundred files - and takes several minutes to load browsing the Media Library, yet the "No items found" message in the dialog comes up within a few seconds.
Any insights or advice are welcome.
| |
I don't think there is an OOTB way to send emails to notify users about approval.
The only way is by creating the script.
The following script goes through the following high-level steps:
Check if a given named email template exists, and create a simple empty one, if it doesn’t
Retrieve the Content Managers Group
Retrieve all usernames from the group
Send notification email using the email template and retrieved usernames
using Stylelabs.M.Base.Querying;
using Stylelabs.M.Sdk.Contracts.Base;
using Stylelabs.M.Sdk.Contracts.Notifications;
using Stylelabs.M.Sdk.Models.Notifications;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
const string emailTemplatename = "Asset Acceptance Notification";
SendEmailAsync();
public async Task SendEmailAsync()
{
var rejectionTemplate = await MClient.Notifications.GetMailTemplateAsync(emailTemplatename);
if (rejectionTemplate == null)
{
await CreateEmailTemaplateAsync();
rejectionTemplate = await MClient.Notifications.GetMailTemplateAsync(emailTemplatename);
}
var groupId = MClient.Users.GetUserGroupAsync("Content Managers").Result.Id;
var query = Query.CreateQuery(entities =>
from e in entities
where e.DefinitionName == "User"
select e);
var users = MClient.Querying.QueryAsync(query, new EntityLoadConfiguration { RelationLoadOption = RelationLoadOption.All}).Result;
var groupUsers = new List<IEntity>();
foreach(var user in users.Items)
{
var groupRelation = user.GetRelation<IChildToManyParentsRelation>("UserGroupToUser");
if (groupRelation.Parents.Contains(group.Id ?? 0)) // nullable ID, provide fallback
{
groupUsers.Add(user);
}
}
var userNames = MClient.Users.GetUsernamesAsync(groupUsers.Select(i => i.Id ?? 0).ToList()).Result?.Select(i => i.Value).ToList();
var notificationRequest = new MailRequestByUsername
{
MailTemplateName = emailTemplatename,
Recipients = userNames
};
var entityModified = Context.Target as IEntity;
notificationRequest.Variables.Add("AssetUrl", "https://somedomain.stylelabsdemo.com/en-us/asset/"+entityModified.Id);
await MClient.Notifications.SendEmailNotificationAsync(notificationRequest);
}
public async Task CreateEmailTemaplateAsync()
{
var enUs = CultureInfo.GetCultureInfo("en-US");
var template = await MClient.EntityFactory.CreateAsync(Stylelabs.M.Sdk.Constants.MailTemplate.DefinitionName) as IMailTemplate;
template.Name = emailTemplatename;
template.SetSubject(enUs, "Asset Approved");
template.SetBody(enUs, "Hello, the following asset got approved: {{AssetUrl}}");
template.SetDescription(enUs, emailTemplatename);
template.SetTemplateVariables(new[] {
new TemplateVariable
{
Name = "AssetUrl",
VariableType = TemplateVariableType.String
}
});
await MClient.Entities.SaveAsync(template);
}
You can view below link for more detail - https://www.cmsbestpractices.com/how-to-send-emails-in-sitecore-content-hub/
| Send e-mail notification when an Asset is submitted for approval
I want to be able to notify a user/ user group when an Asset is submitted for Approval.
Is there a way to do this without needing to create a script?
Thank you.
| |
There is no disconnect, but you obviously need to update the Unicorn.TargetDataStore.config to match your Helix-type setup. Which, as Michael points out as well, is not what I would recommend.
In case you are wondering; you're basically going to have to mount your entire .\src directory into your container to expose all the .yml files; make sure you define a very adequate .dockerignore if going down this route.
Also keep in mind; from your question it looks like you may be overlooking this fact; what you define in your Unicorn.TargetDataStore.config is a path relative to your docker container and NOT your source filesystem as it sits on your host machine.
By default, I recommend not deploying a datastore definition to containers at all. This will cause Unicorn to use ~\App_Data\Unicorn as its default. You can then volume mount your .\src directory to here if you like.
All in all though, bottom line, this is a very clunky approach and you really shouldn't be mixing up your serialised content assets with your source code assets. Make your Unicorn root .\Unicorn relative to your GIT repository root, and be done with the hassle.
This best practice is demonstrated in the GIST you linked; here: https://gist.github.com/cassidydotdk/47eacabd752d7a84e7e5826531fb0f9e#file-docker-compose-yml-L7
| How to define Unicorn configuration for a Helix type serialization folder structure with Docker
I have followed this article https://gist.github.com/cassidydotdk/47eacabd752d7a84e7e5826531fb0f9e
The docker site is writing to the C:\unicorn and the mount volume is set to the D:\Sitecore\Source\unicorn but my helix code structure as below
D:\Sitecore\Source\src\Feature\Account\code
D:\Sitecore\Source\src\Feature\Account\serialization
In the account feature example, the unicorn.yml files should be written to
D:\Sitecore\Source\src\Feature\Account\serialization
to check in and share with other developers etc however the files from docker are coming to
D:\Sitecore\Source\unicorn\Feature\Account\serialization
There is a disconnect and missing some configuration here,
| |
If you look at the configs, you can see that there's no processor to optimize an SVG to a WebP, and if you look at the webp optimizer, it doesn't accept an SVG. This conversion seems like it would only make sense if you have raster graphics in your SVGs, and the solution there is to get them out and convert.
https://developers.google.com/speed/webp/docs/cwebp
https://github.com/kamsar/Dianoga/blob/master/src/Dianoga/Default%20Config%20Files/z.01.Dianoga.NextGenFormats.WebP.config.disabled
| SVGs files are not getting converted to WEBP format using Dianoga
We have added Dianoga to our Sitecore which should convert JPEG, ONG, and SVG to Webp format but can someone explain to me why my SVG files are not getting converted?
I have no error in logs, the files are not getting converted in logs as well. Other file types are getting converted. Also, I have the following config in Sitecore:
<mediaLibrary>
<mediaTypes>
<mediaType name="SVG image" extensions="svg">
<mimeType>image/svg+xml</mimeType>
<forceDownload>false</forceDownload>
<sharedTemplate>system/media/unversioned/image</sharedTemplate>
<versionedTemplate>system/media/versioned/image</versionedTemplate>
</mediaType>
</mediaTypes>
</mediaLibrary>
Also, I have added Dianoga.svgtools NuGet package to the solution.
Can someone suggest to me why it is happening and how can we solve it?
I have enabled the file: https://github.com/kamsar/Dianoga/blob/master/src/Dianoga/Default%20Config%20Files/z.01.Dianoga.NextGenFormats.WebP.config.disabled
Also, the logs are like:
21784 18:07:41 INFO Dianoga: optimized /abcImages/Casestudy Logo/NGL.png [original size: 8847 bytes] [final size: 5296 bytes] [saved 3551 bytes / 40.14%] [Optimized in 447ms] [Extension webp]
21784 18:07:42 INFO Dianoga: optimized /abcImages/Casestudy Logo/sunpower-250-90.svg [original size: 15230 bytes] [final size: 11643 bytes] [saved 3587 bytes / 23.55%] [Optimized in 1528ms] [Extension svg]
If you see png is getting converted but webp is not.
| |
I don't think there is anything wrong with your setup.
It looks like your paths in the file system would be too long so Unicorn decided for some of them to keep IDs instead of full paths.
You can check setting:
<!-- Rainbow - SERIALIZATION FOLDER PATH MAX LENGTH
In Windows, there is 248 characters limit on the lenght of file system paths. To avoid exceeding the maximum path length, Rainbow will loop
long paths back to the root. This setting specifies the maximum length of the path to the serialization root path,
which determines how long item paths can be before they are looped.
Important: The value of this setting must be the same on all Sitecore instances accessing the serialized data.
Important: When changing this value, you must reserialize all configurations!
Example: A value of "90" for this setting will mean that item paths longer than 150 characters will be shortened, since Sitecore
reserves 8 characters (and 248 - 8 - 90 = 150).
Default value: 90
-->
<setting name="Rainbow.SFS.SerializationFolderPathMaxLength" value="190" />
| Unicorn Serialization Items appear as Ids in file system
I have a problem when using unicorn serialization for Sitecore items, when I perform the initial serialization for the item and check the folder in the file system the items come like that
I believe this happens with items that have many children items. below is the configuration for my site
<configuration name="Feature.ATLP.Renderings.Serialization" description="ATLP Feature Serialization">
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Feature\Renderings" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate>
<include name="Renderings.Feature.ATLP" database="master" path="/sitecore/layout/Renderings/Feature/atlp-informational-web"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Templates.Serialization" description="ATLP Project Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Templates" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Templates.Project.ATLP" database="master" path="/sitecore/templates/Project/atlp-informational-web"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Layouts.Serialization" description="ATLP Project Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Layouts" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Layouts.Project.ATLP" database="master" path="/sitecore/layout/Layouts/Project/atlp-informational-web"/>
<include name="PlaceholderSettings.Project.ATLP" database="master" path="/sitecore/layout/Placeholder Settings/Project/atlp-informational-web"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Media.Serialization" description="ATLP.Project.Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Media" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Media.Project.ATLP" database="master" path="/sitecore/media library/Project/atlp/atlp-informational-web"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Content.Serialization" description="ATLP.Project.Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Content" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Content.Home.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/home"/>
<include name="Content.Data.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/Data"/>
<include name="Content.Dictionary.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/atlp-informational-web Dictionary"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Presentation.Serialization" description="ATLP.Project.Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Presentation" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Presentation.Styles.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/Presentation/Styles"/>
<include name="Presentation.PartialDesigns.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/Presentation/Partial Designs"/>
<include name="Presentation.PageDesigns.ATLP" database="master" path="/sitecore/content/AbuDhabiPorts/ATLP/atlp-informational-web/Presentation/Page Designs"/>
</predicate>
</configuration>
<configuration name="Project.ATLP.Forms.Serialization" description="ATLP.Project.Serialization" >
<targetDataStore physicalRootPath="$(AtlpSerilizationFolder)\ATLP\Project\Forms" useDataCache="false" type="Rainbow.Storage.SerializationFileSystemDataStore, Rainbow" singleInstance="true"/>
<predicate type="Unicorn.Predicates.SerializationPresetPredicate, Unicorn" singleInstance="true">
<include name="Forms.ATLP" database="master" path="/sitecore/Forms/atlp-informational-web"/>
</predicate>
</configuration>
</configurations>
</unicorn>
Any advice what is wrong here?
| |
If you are asking about clicking on the icon on Launchpad:
Open /sitecore/client/Applications/Launchpad/PageSettings/Buttons/ContentEditing/Horizon item in core database
There is PathResolver field (that has value Sitecore.Horizon.Integration.LaunchPad.HorizonHostResolver, Sitecore.Horizon.Integration)
You can override this class and assembly to yours
The default logic of getting Horizon site looks in this way:
public virtual string Execute()
{
string clientHost = _settings.Horizon().ClientHost;
string clientHostStartPage = _settings.Horizon().ClientHostStartPage;
string text = clientHost + clientHostStartPage;
string text2 = _sitecoreContextHelper.Context.HttpContext?.Request.Url?.Host;
string text3 = ((text2 != null) ? _siteManager.TryBestMatchClientSiteByHost(text2) : null);
if (text3 != null)
{
return text + "?sc_site=" + text3;
}
return text;
}
| Setting the default site in horizon
Hey guys we have a multi site setup, when we open horizon it does not open the correct site. Does anyone know where we can set the default site for horizon in sitecore 10.2?
| |
It turned out that the 9.1 version of this file was being used instead of the 10.2 version Sitecore.Owin.Authentication.IdentityServer.config - the important difference was on the following line:
Sitecore 9.1 version:
<map name="set IsAdministrator" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication">
Sitecore 10.2 version:
<map name="set IsAdministrator" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication" resolve="true">
Note: resolve="true" is now set on this type.
| Sitecore 10.2.1 (pre release) error loading hook
We are upgrading from 9.1 to 10.2.1 (pre release) and we're seeing this error when trying to load the CM instance:
11608 17:56:05 WARN Could not find constructor in ReflectionUtil.CreateObject: Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper. The constructor parameters may not match or it may be an abstract class. Parameter info: Count: 0
11608 17:56:05 ERROR Error loading hook: <hook type="Sitecore.ContentSearch.Hooks.Initializer, Sitecore.ContentSearch" patch:source="Sitecore.ContentSearch.config" xmlns:patch="http://www.sitecore.net/xmlconfig/" />
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Sitecore.Configuration.DefaultFactory.AssignProperties(Object obj, Object[] properties)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert)
at Sitecore.ContentSearch.ContentSearchManager.get_SearchConfiguration()
at Sitecore.ContentSearch.Hooks.Initializer.Initialize()
at Sitecore.Events.Hooks.HookManager.LoadAll()
Nested exceptions:
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Sitecore.Reflection.ReflectionUtil.CreateObject(Type type, Object[] parameters)
at Sitecore.ContentSearch.DocumentBuilderOptions.CreateComputedIndexField(String fieldName, XmlNode configNode)
at Sitecore.ContentSearch.SolrProvider.SolrDocumentBuilderOptions.AddComputedIndexField(XmlNode configNode)
Nested Exception
Exception: Sitecore.Exceptions.ConfigurationException
Message: Could not create instance of type: Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper. No matching constructor was found. Constructor parameters:
Source: Sitecore.Kernel
at Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, Boolean assert)
at Sitecore.Configuration.DefaultFactory.CreateObject[T](XmlNode configNode)
at Sitecore.Owin.Authentication.Infrastructure.ServicesConfigurator.<>c.<Configure>b__0_0(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Sitecore.DependencyInjection.LazyResetable`1.get_Value()
at Sitecore.Context.ContextData.get_User()
at Sitecore.Context.get_Culture()
at Sitecore.DateUtil.ParseTimeSpan(String time)
at Sitecore.Configuration.Settings.GetTimeSpanSetting(String name, String defaultValue)
at Sitecore.ContentTesting.Analytics.Reporting.SiteNameQuery..ctor()
at Sitecore.ContentTesting.Helpers.SiteHelper..ctor()
at Sitecore.ContentTesting.ContentSearch.ComputedIndexFields.ItemSite..ctor()
Everything works fine on a local dev instance and everything worked fine up until the point the project files were deployed. I have been checking differences in the web.config to resolve other unrelated issues but couldn't see anything obvious related to this.
The DefaultClaimToPropertyMapper requires a BaseLog
| |
It appears that using the redirectMode="ResponseRedirect" attribute uses Server.Transfer behind the scenes so relative routes will not work with the older .net MVC 4.8 framework. This is not a Sitecore specific issue.
I managed to get it to trigger by removing redirectMode attribute and adding
responseMode="file", this allowed me to serve a static html page.
Transform snippet is as follows...
<customErrors mode="RemoteOnly" xdt:Transform="Replace" defaultRedirect="/ErrorPage.html" >
<error statusCode="500" redirect="/ErrorPage.html" responseMode="File"/>
</customErrors>
| Issue with custom errors configuration in my Sitecore 10.1 instance
I am facing an issue whereby custom errors are not redirecting to error page configured.
I have custom errors remote only set in the web.config as below:
<customErrors mode="RemoteOnly" xdt:Transform="Replace" redirectMode="ResponseRewrite">
<error statusCode="500" redirect="/ErrorPage.aspx" />
</customErrors>
And an ErrorPage.aspx within the root of the application. It appears that this is not being caught though.
Is there something different within Sitecore 10 that prevents this to previous versions?
| |
You'll want to either cast the field to the proper field type or use the PSFields collection to access it for you.
Read more here.
Example: The following gets the home item of a site, accesses the HeroImage field and expands the Alt text.
$item = Get-Item -Path "master:" -ID "{961563FC-3445-4558-BF3A-06DF06BA6298}"
$item.PSFields.HeroImage.Alt
Update
Based on your revised requirements here is what I've learned.
When accessing the Alt field on the ImageField type the text is first extracted from the xml in the field followed by a fallback to the text on the media item. Doesn't appear that the Alt property provides a way to know whether or not it's the default value.
You could try something like the following:
$item = Get-Item -Path "master:" -ID "{961563FC-3445-4558-BF3A-06DF06BA6298}"
$detectedValue = $item.PSFields.HeroImage.Alt
$defaultValue = $item.PSFields.HeroImage.MediaItem["Alt"]
if($defaultValue -ne $detectedValue) {
Write-Host "This has been overridden"
} else {
Write-Host "This is the default value"
}
$rawValue = $item.PSFields.HeroImage.GetAttribute("alt")
if($detectedValue -ne $rawValue) {
Write-Host "It's showing the default value"
}
"ABC" is stored in $rawValue and $detectedValue. If I cleared it out $detectedValue would match $defaultValue and $rawValue would be blank.
| How to read Item's media field properties using SPE
I have an item where we have a "Article Thumbnail" field(Media type) and an image is inserted from Media Library.
Now I need to check for Alt text in Item's media properties. I am trying with below script and finding an odd behavior. When I browse for Item's field, I see an empty alt. But when I do selection for that field, it is going to its media library item and fetching me the alt. So, how to get correct Item's Image alt ?
To be more clear, see the highlighted part (Alternate Text and Default Alternate Text)
| |
For Sitecore 10.0, the only version of the CLI that you can use is 2.0.0 (https://dev.sitecore.net/Downloads/Sitecore_CLI/2x/Sitecore_CLI_200.aspx)
Source: https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1000576
All versions above require Sitecore 10.1+
| Sitecore Serialization using Sitecore CLI Installation Error
I am attempting to install Sitecore CLI 4.2.1 on Sitecore 10.0. The installation is fresh install of Sitecore 10.0. I keep getting this error below. This error will shut down Sitecore where I have to restore the files from a backup of files. All help is appreciated to resolve:
Server Error in '/' Application.
Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
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.IO.FileLoadException: Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
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.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +96
System.Type.GetType(String typeName) +62
Sitecore.DependencyInjection.<>c.<GetServicesConfigurators>b__2_0(XmlNode x) +114
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +241
Sitecore.DependencyInjection.BaseServicesConfiguratorFactory.Configure(IServiceCollection serviceCollection) +193
Sitecore.DependencyInjection.BaseServicesConfiguratorFactory.Configure(IServiceCollection serviceCollection) +171
Sitecore.DependencyInjection.BaseServiceProviderBuilder.ConfigureServiceCollection() +142
Sitecore.DependencyInjection.ServiceLocator.ConfigureServiceProvider() +225
Sitecore.DependencyInjection.ServiceLocator.get_ServiceProvider() +513
Sitecore.DependencyInjection.SitecorePerRequestScopeModule..ctor() +13
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +142
System.Activator.CreateInstance(Type type, Boolean nonPublic) +107
System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) +1476
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +186
System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +28
System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +80
System.Web.HttpApplication.BuildIntegratedModuleCollection(List`1 moduleList) +234
System.Web.HttpApplication.GetModuleCollection(IntPtr appContext) +1153
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +139
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +277
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4494.0
| |
In the reports view rendered when calling Show-ListView a "report actions" button can be added that modify the existing data.
Read more here.
In show you would perform the following steps.
Save an item in the tree representing the action button.
Assign a rule to the action button script so it only appears for a specified view name.
Update your call to Show-ListView to specify the view name.
If you look at the Training module you should see a sample.
The action appears at the top right of the report.
This action can then call whatever script you want.
| Read-Variable inside listview?
I have a listview of various items and I would want there to be a dropdown box in the listview that lets the user change one of the items results. Is this possible?
I am trying to set a property that holds selection options (IE Option1, Option2..etc.). It gets populated but it doesn't show up inside the listview.
I tried read-variable in the Show-ListView like below but it did not work-
Get-ChildItem -Path $targetD -Recurse | Where-Object { $myItems.ContainsValue($_.TemplateName) } |
Show-ListView -Property @{Label="Name"; Expression={ $_.DisplayName } },
@{Label="Path"; Expression={ $_.Paths.Path } },
@{Label="Current"; Expression={ $_.Name } },
@{Label="Desired"; Expression={ Read-Variable @props } }`
-Title "Data to be transferred"`
-Modal
I also considered perhaps setting each item in the list to have an already filled response of "none" that can be changed by the user, so that it isn't null when opening, but I wasn't sure if that's going to work either. Is it even possible to have selection fields in the listview at all?
| |
Instead of using get-item you need to use Get-ChildItem to achieve this.
So your query will look like this.
$acl2 = New-ItemAcl -AccessRight item:write -PropagationType Descendants -SecurityPermission AllowAccess -Identity "default\Everyone"
Get-ChildItem master:\content\home | Set-ItemAcl -AccessRules $acl1, $acl2 -PassThru
If will set the Write access to all the child items under the home node. So the resulting output will be this.
| PropagationType in Sitecore powershell scirpt is not working
I was trying to deny write access to Everyone role for my Sitecore Content tree nodes. There are many nodes and lot of items have write access for Everyone user , which we want to restrict now.
I tried using below scirpt , but it only works with the single item and not propagating to its children.
I used PropagationType as Any and Descendants both but it does not propagate to its child level. As a work around , I have to loop through the tree items and run the command.
$acl1 = New-ItemAcl -AccessRight write -PropagationType Any -SecurityPermission DenyAccess -Identity Everyone
Instead of this line
foreach($item in $items)
{
$item|Set-ItemAcl -AccessRules $acl1
}
I want to do
get-item -Path "master:content/My-Node/Home |Set-ItemAcl -AccessRules $acl1
to reflect the write access restriction to all the child items under Home.
I am not sure if it is a bug or I am doing it wrongly .. If you have come across this, your guidance would be helpful.
I used Sitecore 9.3 rev. 003498.
| |
As a Solution to be able to run Sitecore PowerShell Script, e.t.c. Is change the elevationAction in the config to Allow or Confirm, then you don't need to enter a password.
Set the elevationAction can be done by setting the environment var SITECORE_SPE_ELEVATION in your docker-compose.yml
the patch file \Include\v.Spe\s.Spe.config is using this environment var, $(env:SITECORE_SPE_ELEVATION)
Or patch it your self but be sure it is after the s.Spe.config, place in a zz_spe folder for example.
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore role:require="XMCloud">
<powershell>
<userAccountControl>
<tokens><token name="Default" elevationAction="Block"/>
<token name="Console" expiration="00:05:00" elevationAction="Allow" patch:instead="*[@name='Console']"/>
<token name="ISE" expiration="00:05:00" elevationAction="Allow" patch:instead="*[@name='ISE']"/>
<token name="ItemSave" expiration="00:05:00" elevationAction="Allow" patch:instead="*[@name='ItemSave']"/>
</tokens>
</userAccountControl>
</powershell>
</sitecore>
</configuration>
| PowerShell Elevate Session State on XM Cloud
How can I perform an Elevate Session State in Sitecore PowerShell ISE on XM Cloud running in local container?
On the Elevate Session State, I need to "Enter your credentials to validate access to Execute a script." it tries to use my xmcloud username but it gives an error message
Could not validate access using the provided credentials.
Or else how can I execute and create PowerShell scripts?
| |
I have tried running this query via Postman and the syntax seems fine to me. Just follow the below steps to make this work.
First of all, You will need to use this method to authenticate users. It sets the authentication cookie.
https://<your server>/sitecore/api/ssc/auth/login
Make sure you are passing, Content-Type:application/json in the headers.
Now, Use the below query to run a Sitecore search that is stored in a search definition item. This means you will need to first create a Search definition item in the Sitecore content tree based on the template /sitecore/templates/System/Services/Item Service/Search/Search Definition. You can provide details for this item like database, field name etc.
Now, run the query on this item,
<your server>/sitecore/api/ssc/item/FDFFA0FA-40D4-47F6-87CD-7BC3B1EA6EC2/search?term=Home&database=master
In the result, you would see all the items having search terms in the defined fields
| Stored Sitecore search using API returns 400 error
I am trying to use stored Sitecore search using an API call from console application, but it is throwing 400 error. I have followed the sitecore documentation
https://doc.sitecore.com/xp/en/developers/102/sitecore-experience-manager/the-restful-api-for-the-itemservice.html
under the last section "Run a stored Sitecore search" section with the URL format provided. The URL which I provided is the following -
https://demosc.dev.local/sitecore/api/ssc/item/1FB673FA-C0E0-4174-BA8F-2C170BB71BCD/search?term=State&database=master
It seems the URL structure formed is not correct and I am not sure as I followed the example in the documentation. Kindly help me with the same.
| |
I have been able to recreate the problem you are having locally and as that other post says Sitecore Forms logic is indeed weird!
As that post states, it looks at each condition in order and if its true applies your action, but if not it applies the inverse of the action. The last action to influence an objects state is the one that is applied.
In your case, because you want to hide both sections if radio is empty, you need that to be the last condition (otherwise the other radio conditions would make one of the section show if applied after). The problem is though... by adding that condition as last condition, when it is not true (i.e. radio selected) the INVERSE is applied last - so both are set to show.
I dont believe it is therefore possible to add a set of conditions to achieve your goal, based on the current layout of your page.
My suggestion would be to add an invisible parent section, that surrounds the other two sections. Then apply a single condition referencing that. So if radio is empty, hide the parent section.
You can then apply a further condition, stating if radio is equal to "Credit Union", show/hide sections within the parent. Note, due to the fact the inverse will be applied if NOT true, you only need the one condition adding, because if it is not equal to "Credit Union" then the inverse is to hide credit union and show organization name section.
Hopefully the screenshot below shows what I mean.
| Sitecore 10 Conditional Fields with Radio Button
I presently have a form that contains a radio button group with 2 options. I would like that section 1 shows when I pick the first option and section 2 shows when I pick the second.
Currently Section 1 (Credit Union) always shows no matter what I select and upon load.
Here is what I have for my conditions:
I have read this thread: Sitecore 9.1 Forms conditional logic not working as expected and tried to format my condition how they suggested, but they only show 2 options.
| |
One approach to confirm the session data is not being tracked would be to check that the data is not being stored in XConnect database.
First of all confirm data is being stored correctly. A users data is sent to XConnect when their session ends. You could either navigate pages and wait the specified time for session to expire, or you can force the session to be abandoned.
To force the session to be abandoned, create a file called abandon.aspx and copy the contents of the below into it.
<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
}
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server" id="form">
Session Abandoned
</form>
</body>
</html>
Place abandon.aspx at the root of your sitecore instance.
Now to simulate a visit. Navigate to your site, browse across a number of pages, then finally navigate to https://yoursite.com/abandon.aspx
This should then force the session to end and save data to XConnect.
To confirm the data has been stored, find the value of your SC_ANALYTICS_GLOBAL_COOKIE and the necessary dashes to make it into a valid guid, and then convert to UPPER case.
i.e.
88a7b5ce440743fa840ef5ac0aab05e9
becomes
88A7B5CE-4407-43FA-840E-F5AC0AAB05E9
`
This guid is your device profile ID.
Now go to your SQL database that houses XConnect Shard tables and perform this query:
SELECT *
FROM [Sitecore_Xdb.Collection.Shard0].[xdb_collection].[DeviceProfiles]
WHERE DeviceProfileId = 'device-profile-id'
UNION
SELECT *
FROM [Sitecore_Xdb.Collection.Shard1].[xdb_collection].[DeviceProfiles]
WHERE DeviceProfileId = 'device-profile-id'
Note the value of 'LastKnownContactId'.
This is your Contact Id.
Now see the data from your last site visit, perform the following query:
SELECT *
FROM [Sitecore_Xdb.Collection.Shard0].[xdb_collection].[Interactions]
WHERE ContactId = 'your-contact-id'
UNION
SELECT *
FROM [Sitecore_Xdb.Collection.Shard1].[xdb_collection].[Interactions]
WHERE ContactId = 'your-contact-id'
If your Xconnect is setup correctly (and your performed the above actions against a CD or standalone server role). Then you should see the data from your last interaction.
Finally, to confirm that a users data is not being stored. Peform the above actions and confirm that ONLY a user who has requested not to be tracked, does not have there data stored as above.
| Turn Sitecore Analytic Tracking on and Off and test tracking data
We have OneTrust Cookie banner on the site and if the user does not give permission to track Performance Cookies we have a pipeline that turns on/off Sitecore Tracker.
We are not deleting the SC_ANALYTICS_GLOBAL_COOKIE just turning the tracker on/off based on User Preference.
What is the best way to test this in Sitecore. What I want to test is:
If the user turns off Tracking then the user session is not tracked anymore. Is there a parameter in the Sitecore Analytic dashboard that shows session data for all users? Is there is unique session Id created for each session?
Note: We do not have a login on the site
| |
Sitecore PaaS best practices recommend to disable FileSystemWatchers to improve stability of your Sitecore website.
The below is an example of a patch config file to do so:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<watchers>
<patch:delete />
</watchers>
<mediaLibrary>
<watcher>
<ignoreList>
<patch:delete />
</ignoreList>
</watcher>
</mediaLibrary>
</sitecore>
</configuration>
Also, it is recommended to disable the Upload Watcher to improve security of your Sitecore instance and ensure that the only way to upload files to Sitecore is from the Media Library, i.e. you can only upload files from within the Sitecore client and have control over the files that are uploaded. Read more here.
When you disable the Upload Watcher, files that are placed in the upload folder are not automatically uploaded to the Media Library.
To disable the Upload Watcher:
Open your web.config file and remove the following string from the <system.webServer><modules> section:
<add type="Sitecore.Resources.Media.UploadWatcher,Sitecore.Kernel" name="SitecoreUploadWatcher"/>
| Sitecore instance restart caused by a FileSystemWatcher in PaaS
My Sitecore instance deployed onto Azure Web App Service has issues with the FileSystemWatcher forcing it to restart randomly.
How can I improve the stability of my Sitecore website on Azure Web App?
| |
As Marek mentioned you should not use the deny to block access to the other site nodes. If you use the inheritance feature as described on https://doc.sitecore.com/xp/en/developers/102/platform-administration-and-architecture/the-inheritance-access-right.html you will get the same result - editors not being able to see/edit the sites they shouldn't see but you will be able to give certain editors 2 or more roles and enable them this way to edit multiple site nodes as there is no deny anymore that blocks the grants.
| Sitecore Role access to Multiple site nodes in Sitecore
I have sitecore setup with 30 + site nodes ( site-Australia, site-Germany, site-Japan ,site-US etc.) in Sitecore. At present all editors and publishers have access to all of these nodes which in practical not an ideal design.
We want to restrict the access to editors and publishers in such a way that , Australia editor can not edit or see the Germany site node items, similarly US editor can not see or edit items in Australia or German (or any other) site nodes.
As a solution, I created region wise editors and publishers ( Auseditor, Japaneditor ) and allowed read,write, create, rename and inheritance access to that region node and denyed the write access to other nodes. This works fine with individual editors.
Now issue I am facing is , there are editors who need access to 2 or more regions (for eg. ASIA editor who needs access to Australia, Japan nodes) and in that case, since the deny takes the priority over grant, when I add both the roles, that editor is not able to write the content as Japan node denies write access to Australia node and Australia editor role denies the write access to Japan.
The solution I thought for this is to create another role for such "combined" editor roles and give the write access to these multiple nodes. But not sure this is right approach for access rights for multi node solution as we have many nodes and I suspect that we may end up managing such "combined" scenarios as and when required in future which may make the role management tedious and cumbersome. So looking for some simplistic solution thoughts for this design.
If you have come across the situation and have better suggestion/solution please do share.
| |
Thanks a lot Trayek for your response as it helped me to get resolution.
I made changes on both GraphQL query and NextJS component in order to make it working. Now I'm able to edit fields using sitecore experience editor.
below is the changes on GraphQL query applied on sitecore rendering:
query($datasource: String!) {
TestComponent: item(path: $datasource, language: "en") {
id(format: "B")
Heading:field(name:"Heading"){
... on TextField{
jsonValue
}
}
Description:field(name:"Description"){
... on RichTextField{
jsonValue
}
}
}
}
below is the changes on NextJS component:
import { Text, RichText, withDatasourceCheck } from '@sitecore-jss/sitecore-jss-nextjs';
import { ComponentProps } from 'lib/component-props';
type TestProps = ComponentProps & {
fields: {
data: {
TestComponent: {
Heading: {
jsonValue:{
value: string;
};
};
Description: {
jsonValue:{
value: string;
};
};
};
};
//Heading: Field<string>;
//Description: 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 Test = ({ fields }: TestProps): JSX.Element => (
<div className="contentBlock">
<Text tag="h2" className="contentTitle" field={fields.data.TestComponent.Heading.jsonValue} />
<RichText className="contentDescription" field={fields.data.TestComponent.Description.jsonValue} />
</div>
);
export default withDatasourceCheck()<TestProps>(Test);
| Fields not editable in Sitecore Experience Editor when using GraphQL
I'm using Sitecore 10.2 in my local as headless and nextjs for FrontEnd.
I'm able to open the home page on the experience editor and edit fields as well when I use Layout service to fetch data on nextjs w/o using GraphQL on rendering.
but when I apply GraphQL like below on Sitecore rendering, unable to edit the fields on experience editor.
query($datasource: String!) {
TestComponent: item(path: $datasource, language: "en") {
id(format: "B")
Heading:field(name:"Heading"){
... on TextField{
value
}
}
Description:field(name:"Description"){
... on RichTextField{
value
}
}
}
}
below is code for component written on nextjs.
import { Text, RichText, withDatasourceCheck } from '@sitecore-jss/sitecore-jss-nextjs';
import { ComponentProps } from 'lib/component-props';
type TestProps = ComponentProps & {
fields: {
data: {
TestComponent: {
Heading: {
value: string;
};
Description: {
value: string;
};
};
};
//Heading: Field<string>;
//Description: 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 Test = ({ fields }: TestProps): JSX.Element => (
<div className="contentBlock">
<Text tag="h2" className="contentTitle" field={fields.data.TestComponent.Heading} />
<RichText className="contentDescription" field={fields.data.TestComponent.Description} />
</div>
);
export default withDatasourceCheck()<TestProps>(Test);
| |
Control Panel in Sitecore uses sitecore\shell\client\Applications\ControlPanel\ControlPanel.cshtml file, So if you will see the code in this file, it just reads all the children of item ID - {AD6A5F44-088A-450E-9DBE-75DDADC94C57} and create the complete page. This ID is control panel item in core database on following path - /sitecore/content/Applications/Control Panel. you are not able to see the Administration tools so you need to check and sync /sitecore/content/Applications/Control Panel/Administration item and its children.
| Where is the content of the Control Panel stored in Sitecore 9.2
I have performed an upgrade of a solution from 8.2 to 9.2 but can still see some differences in the Control Panel between the upgraded one and a clean instance created by SIF.
I have tried synchronising this item
/sitecore/client/Applications/ControlPanel
from the Core DB, but it doesn't seem to have had any effect. Is there some other place where this is defined in the Core DB or is it in fact a file system artefact which has been missed?
| |
To resolve the above issue and find the solution, I have explored Sitecore.ContentSearch DLL and found out it provides the below method in the IProviderUpdateContext interface.
void AddDocument(object itemToAdd, IExecutionContext executionContext);
void AddDocument(object itemToAdd, params IExecutionContext[] executionContexts);
void Delete(IIndexableUniqueId id, params IExecutionContext[] executionContexts);
void Delete(IIndexableId id, params IExecutionContext[] executionContexts);
void UpdateDocument(object itemToUpdate, object criteriaForUpdate, IExecutionContext executionContext);
In Sitecore 10.2 it takes a parameter object as a type of Dictionary. Hence I updated the code as mentioned below:
var document = new Dictionary<string, object>();
document.Add("_uniqueid", indexable.UniqueId.Value.ToString());
document.Add("_datasource", indexable.DataSource.ToLowerInvariant());
document.Add("_indexname", SearchIndex.Name.ToLowerInvariant());
document.Add("_content", string.Format("{0}|{1}", item.Name, item.ID.ToString()));
//other fields
context.AddDocument(document, indexable.Culture != null ? new CultureExecutionContext(indexable.Culture) : null);
After building and publishing the code it's working perfectly fine and I get the result into the SOLR query.
| Add Custom Fields in SOLR
I am converting the Lucene Search to SOLR while migrating the project from Sitecore version 8.2 to 10.2.
In the current Sitecore version 8.2 of the project Lucene is implemented. I have updated the configuration and all most code-related changes. But in a few of the indexes, there are some custom fields added in Lucene in the schema on SitecoreItemCrawler.
<index id="project_career_master" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<param desc="name">$(id)</param>
<param desc="core">$(id)</param>
<param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
<configuration ref="contentSearch/indexConfigurations/defaultSolrIndexConfiguration" >
<enableReadAccessIndexing>true</enableReadAccessIndexing>
</configuration>
<strategies hint="list:AddStrategy">
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync" />
</strategies>
<locations hint="list:AddCrawler">
<crawler type="project.Website.Indexes.Career.CustomCareerSearchCrawler, project.Website">
<Database>master</Database>
<Root>/sitecore/content/project/Careers</Root>
<Templates>{BB39C081-385F-1421-9T68-70C0RT12DA00}</Templates>
</crawler>
</locations>
</index>
Here in the above configuration, you can see there is a custom crawler written:
<crawler type="project.Website.Indexes.Career.CustomCareerSearchCrawler, project.Website">
Backend Code:
using Lucene.Net.Documents;
public class CustomCareerSearchCrawler : SitecoreItemCrawler
{
public readonly List<ID> _templateIDs = new List<ID>();
public string Templates { get; set; }
public string LanguageName { get; set; }
public override void Initialize(ISearchIndex searchIndex)
{
Assert.IsNotNullOrEmpty(Templates, "TemplateIDs");
var ids = Templates.Split('|');
_templateIDs.Clear();
foreach (var id in ids)
{
_templateIDs.Add(new ID(id));
}
base.Operations = new CustomIndexOperations()
{
TemplateIDs = this._templateIDs,
SearchIndex = searchIndex
};
base.Initialize(searchIndex);
}
}
public class CustomIndexOperations : IIndexOperations
{
public void Add(IIndexable indexable, IProviderUpdateContext context, ProviderIndexConfiguration indexConfiguration)
{
var item = (Item)(indexable as SitecoreIndexableItem);
if (!TemplateIDs.Contains(item.TemplateID))
{
return;
}
var document = new Document();
document.Add(new Field("_uniqueid", indexable.UniqueId.Value.ToString(), Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("_datasource", indexable.DataSource.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("_indexname", SearchIndex.Name.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("_content", string.Format("{0}|{1}", item.Name, item.ID.ToString()), Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("_langauge", item.Language.Name, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("_id", item.ID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("_name", item.Name, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("_title", item["Job Position"], Field.Store.YES, Field.Index.NOT_ANALYZED));
context.AddDocument(document, indexable.Culture != null ? new CultureExecutionContext(indexable.Culture) : null);
}
}
with the same, update and delete method also implemented on Crawler:
public void Update(IIndexable indexable, IProviderUpdateContext context, ProviderIndexConfiguration indexConfiguration)
public void Delete(IIndexableUniqueId indexableUniqueId, IProviderUpdateContext context)
The above backend code is using the Lucene DLL.
I want to implement the same in SOLR, does anyone has inputs for the same, how to rewrite the above backend code in SOLR, please?
| |
Tell your NextJS app to render the fonts using absolute URL.
We did it in our app by setting the PUBLIC_URL variable to the base URL of our app, which in your case, https://www.myapp.localhost.
You will also need to configure your NextJS app to allow cross domain request from your CM hostname. See this doc to see how you can modify http headers in NextJS.
| Missing fonts when previewing Next.js app in Experience Editor
I've got a Next.js-based app that uses custom fonts. On the Rendering host the fonts are accessible via the following url:
https://www.myapp.localhost/_next/static/media/lato-latin-400-normal.b7ffde23.woff2
Experience Editor tries to load fonts from CM but the fonts are not found and 404 is returned:
https://cm.localhost/_next/static/media/lato-latin-400-normal.b7ffde23.woff2
In the same time, the webpack.js file is requested from the Rendering host and successfully received:
https://www.myapp.localhost/_next/static/chunks/webpack.js?ts=1665501553546
How to make Experience Editor request fonts from the Rendering host?
| |
Ah blizz! I shouldn't set the environment variable NODE_TLS_REJECT_UNAUTHORIZED to 0 on the XM Cloud CM server (in the Docker container), but on my dev machine where I run jss start:connected. Now it works!!
| XM Cloud locally with docker compose gives: unable to verify the first certificate
I have XM Cloud running locally in a docker container. This means with self-signed certificates.
When I use JSS to create and deploy the JSS Style guide application, I keep getting the following error when starting my JSS application on http://localhost:3000: FetchError: request to https://xmcloudcm.localhost/sitecore/api/graph/edge failed, reason: unable to verify the first certificate
With the built-in GraphiQL explorer on URL https://xmcloudcm.localhost/sitecore/api/graph/edge/ui I can execute GraphQL queries on the endpoint https://xmcloudcm.localhost/sitecore/api/graph/edge.
This does not work with Insomnia offline GraphQL API client, I get the following error
When I disable validate certificates in the settings of Insomnia it works:
I tried to set the environment variable ENV NODE_TLS_REJECT_UNAUTHORIZED "0" in the Dockerfile for the CM server, but that did not help.
Any ideas to get this working in an docker containers based environment with self-signed certificates?
| |
Both the dictionary service and the sitemap service need a root item ID. This root item ID must be configured in two files:
<jss-app>\src\lib\dictionary-service-factory.ts
<jss-app>\src\lib\sitemap-fetcher\plugins\graphql-sitemap-service.ts
In both files, the comments described how to solve the issue.
For <jss-app>\src\lib\dictionary-service-factory.ts:
For <jss-app>\src\lib\sitemap-fetcher\plugins\graphql-sitemap-service.ts:
And the GUID to be used is the template ID of the home item of your JSS app:
| How to solve JSS application error "Error: Valid value for rootItemId not provided and failed to auto-resolve app root item."
When I deploy a JSS Next.js application to Sitecore (XM Cloud on local container, Sitecore demo portal) I get the following error when I run my Next.js application on http://localhost:3000:
In text:
Server Error
Error: Valid value for rootItemId not provided and failed to auto-resolve app root item.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Using JSS version 20.1.3
How can this error be prevented?
| |
Just follow the tips in the config file that you have:
IMPORTANT: JSS sites ship in 'live mode', which makes development and testing easy,
but disables workflow and publishing. Before going to production, change the `database`
below to `web` instead of `master`.
Changing database to web will be enough for your case.
Sitecore Experience Editor (and Horizon as well) works through http://localhost:3000/api/editing/render endpoint. And it will pass all the data from the master DB during editing. It doesn't take into account database property in the site configuration.
Next.js website itself works through requests to Layout Service. And you are able to configure the database that should be used in your site configuration.
| Editing content on Experience Editor on master db and fetch data from web db for Sitecore JSS with NextJS
I'm using Sitecore 10.2 in my local as headless and nextjs for FrontEnd. I'm able to open the home page on the experience editor and can update content.
in Sitecore JSS with next js, we dont need to deploy next js deployable files into sitecore cm/cd instance instead of that we are providing next js app Url(http://localhost:3000) like below.
what I want is that when I run nextjs app it should display content from web db and when I open pages in experience editor it should fetch data from master db and update to master db only and we can publish to copy changes into web db.
but in below configuration I can make it either for master or web not solving both purpose.
even same issue will be there when I deploy to server like dev/staging.
mynextjsapp.config:
<!--
JSS Sitecore Configuration Patch File
This configuration file registers the JSS site with Sitecore, and configures the Layout Service
to work with it. Config patches need to be deployed to the Sitecore server.
Normally `jss deploy config` can do this for local development. To manually deploy, or to deploy via CI,
this file can be placed in the `App_Config/Include` folder, or a subfolder of it, within the Sitecore site.
-->
<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>
<!--
Note that if any of these settings are enabled, they will apply to the entire Sitecore instance. If there are
multiple sites defined in the instances, the settings will affect all of them.
-->
<settings>
<!--
ANALYTICS FORWARDED REQUEST HEADER
When using Next.js SSR routes, Layout Service requests will send the original IP address of the client on the 'X-Forwarded-For' header.
This setting tells Sitecore to read the forwarded header, thus making analytics track the correct original client IP address.
<setting name="Analytics.ForwardedRequestHttpHeader" set:value="X-Forwarded-For" />
-->
<setting name="JavaScriptServices.ViewEngine.Http.JssEditingSecret" value="x889f4myl9iw8hdls9syqb0wuuv3tqs8uaro3vl15" />
<!--
ANALYTICS DISABLE ROBOT DETECTION
During development, activity will flag us as a robot.
These settings will enable tracking of robot activity for ease of testing (development ONLY).
<setting name="Analytics.AutoDetectBots" set:value="false" />
<setting name="Analytics.Robots.IgnoreRobots" set:value="false" />
-->
<!--
JSS EDITING SECRET
To secure the Experience Editor endpoint exposed by your Next.js app (see `serverSideRenderingEngineEndpointUrl` below),
a secret token is used. This is taken from an env variable by default, but could be patched and set directly by uncommenting.
This (server-side) value must match your client-side value, which is configured by the JSS_EDITING_SECRET env variable (see the Next.js .env file).
We recommend an alphanumeric value of at least 16 characters.
<setting name="JavaScriptServices.ViewEngine.Http.JssEditingSecret" value="" />
-->
<!--
LANGUAGE FALLBACK
These settings enable item-level language fallback for JSS apps that use Experience Edge.
In addition to these settings, ensure that Language Fallback is configured on the Language
item in Sitecore, and that items in the content tree have "Enable Item Fallback" field set
to true. Other settings related to item-level language fallback that may exist in Sitecore
configuration will not impact Edge functionality.
<setting name="ExperienceEdge.EnableItemLanguageFallback" value="true"/>
<setting name="ExperienceEdge.EnableFieldLanguageFallback" value="true"/>
-->
</settings>
<sites>
<!--
JSS Site Registration
This configures the site with Sitecore - i.e. host headers, item paths.
If your JSS app lives within an existing Sitecore site, this may not be necessary.
IMPORTANT: JSS sites ship in 'live mode', which makes development and testing easy,
but disables workflow and publishing. Before going to production, change the `database`
below to `web` instead of `master`.
-->
<!--<site patch:before="site[@name='website']"
inherits="website"
name="mynextjssite"
hostName="sitecore10.2sc.dev.local"
rootPath="/sitecore/content/mynextjsapp"
startItem="/home"
database="master" />-->
</sites>
<javaScriptServices>
<apps>
<!--
JSS App Registration
The JSS app needs to be registered in order to support layout service and import services.
There are many available attributes, and they inherit the defaults if not explicitly specified here.
Defaults are defined in `/App_Config/Sitecore/JavaScriptServices/Sitecore.JavaScriptServices.Apps.config`
NOTE: graphQLEndpoint enables _Integrated GraphQL_. If not using integrated GraphQL, it can be removed.
NOTE: layoutServiceConfiguration should be set to "default" when using GraphQL Edge schema.
When using integrated GraphQL with Edge schema, a $language value is injected
since language is required in all Edge queries. "jss" configuration does not do this (which is backwards
compatible with JSS versions < 18.0.0).
-->
<app name="mynextjsapp"
layoutServiceConfiguration="default"
sitecorePath="/sitecore/content/mynextjsapp"
useLanguageSpecificLayout="true"
graphQLEndpoint="/sitecore/api/graph/edge"
inherits="defaults"
serverSideRenderingEngine="http"
serverSideRenderingEngineEndpointUrl="http://localhost:3000/api/editing/render"
serverSideRenderingEngineApplicationUrl="http://localhost:3000"
/>
</apps>
<!--
IMAGE RESIZING WHITELIST
Using Sitecore server-side media resizing (i.e. the `imageParams` or `srcSet` props on the `<Image/>` helper component)
could expose your Sitecore server to a denial-of-service attack by rescaling an image with many arbitrary dimensions.
In JSS resizing param sets that are unknown are rejected by a whitelist.
Sets of image sizing parameters that are used in app components must be whitelisted here.
If a param set is not whitelisted, the image will be returned _without resizing_.
To determine the image parameters being used, look at the query string on the `src` of the rendered image, i.e. '/img.jpg?mw=100&h=72' -> mw=100,h=72
Note: the parameter sets defined here are comma-delimited (,) instead of &-delimited like the query string. Multiple sets are endline-delimited.
-->
<allowedMediaParams>
<!-- XML element name is arbitary, useful for organizing and patching -->
<styleguide-image-sample>
mw=100,mh=50
</styleguide-image-sample>
<styleguide-image-sample-adaptive>
mw=300
mw=100
</styleguide-image-sample-adaptive>
</allowedMediaParams>
</javaScriptServices>
<!--
Media URLs resolving
Tells Sitecore to not include the Sitecore server URL as part of the media requests, so that they are instead routed through Next.js rewrites (see next.config.js).
This eliminates exposing the Sitecore server publicly.
"default" configuration is used for Sitecore GraphQL Edge requests.
"jss" configuration is used for Sitecore Layout Service REST requests.
-->
<layoutService>
<configurations>
<config name="default">
<rendering>
<renderingContentsResolver>
<IncludeServerUrlInMediaUrls>false</IncludeServerUrlInMediaUrls>
</renderingContentsResolver>
</rendering>
</config>
<config name="jss">
<rendering>
<renderingContentsResolver>
<IncludeServerUrlInMediaUrls>false</IncludeServerUrlInMediaUrls>
</renderingContentsResolver>
</rendering>
</config>
</configurations>
</layoutService>
</sitecore>
</configuration>
mynextjsapp.deploysecret.config:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<javaScriptServices>
<apps>
<app name="mynextjsapp"
deploymentSecret="x889f4myl9iw8hdls9syqb0wuuv3tqs8uaro3vl15"
debugSecurity="false"
/>
</apps>
</javaScriptServices>
</sitecore>
</configuration>
| |
The JSS NextImage component is a field rendering helper component that you use to display images configured in Sitecore fields with a Next.js Image component.
The JSS NextImage component uses a custom loader that passes the src property to the next/image component, but you can provide your own loader if required with the help of the loader property.
The following table contains the properties you can use to configure the NextImage component:
shows how to display a responsive, optimized, editable image: -
<NextImage field={props.fields.image} height="51" width="204" />
below example shows how to display a non-editable image where you control the resizing and editing:
<NextImage
field={props.fields.image}
editable={false}
unoptimized={true}
imageParams={{ mw: 100, mh: 50 }}
height="50"
width="94"/>
reference- https://doc.sitecore.com/xp/en/developers/hd/201/sitecore-headless-development/configuring-the-jss-nextimage-component.html
| making image editable in experience editor in sitecore jss with nextjs
I'm using Sitecore 10.2 in my local as headless and nextjs for FrontEnd. I'm able to open the home page on the experience editor and able to update content on Text/RichText html elements.
I'm using GraphQL in rendering.
How can I fetch image in nextjs component and at the same time should be editable from experience editor.
Thanks.
| |
The short answer is no.
It is not possible to change the default url of xmcloudcm.localhost - this is a restriction as you expected, that the url must be whitelisted for the auth0 redirects. Because the authentication provider is hosted by Sitecore, it would not be scalable to add every combination of development url into the whitelist, so there is just this one that you can use for local development.
If you want to have an instance of XM Cloud exposed to the outside world, it would be better to create a new environment in your XM Cloud project and use that.
| Is it possible to give a different hostname than xmcloudcm.localhost to the xmcloud docker container?
By default the CM_HOST value in the init.ps1 file of a XM Cloud project is set to xmcloud.localhost. I want to change this name to, for example xmcloudserge.loca.lt.
If I change the name I get a problem with the authentication from https://xmcloudserge.local.lt to sitecorecloud.io, which contains a hard reference to xmcloud.localhost as a return URL:
https://auth.sitecorecloud.io/authorize?client_id=we67e2gGRO0HIfglz23Yypp4T5Rshu86&response_type=code&scope=openid%20profile&state=OpenIdConnect.AuthenticationProperties%3DE7FEVVpMc5sJM8SLjOlOU_m73gkTqvOfFxs2LrcnaZdSrX3MRF_Q12ZyVDpbKIXZhDDWImasq51g1-y5BGIXOsq21vxGGb8FJjz12NttbaecPcQ8z9Kd0Fnrv5yZmRk0Fjf3TntIMUw2WT628TXtyfEeHhJ8gbaem0rO08GVln8TwzKDJR4qEg7nxqEbucvf7Bt1KMCg_FjD0VdxC2m1hq0WEZ5zfKLTTf_fYOg0-d0&response_mode=form_post&nonce=638012677311361499.Y2ZmMWYzMjUtNjRkZS00NDJjLWI0YzctZjZmZWNmOWUyZWRiZGIwZGE5NzEtNDYwMS00YmU0LWJlMzItZTU5MWVmNDc5MDBj&redirect_uri=https%3A%2F%2Fxmcloudcm.localhost%2Fidentity%2Fsignin-auth0&organization_id=&returnTo=https%3A%2F%2Fxmcloudcm.localhost%2Fsitecore&x-client-SKU=ID_NET461&x-client-ver=5.3.0.0
If I change the returnTo query-string parameter to https://xmcloudserge.local.lt I get the following error:
Callback URL mismatch.
The provided redirect_uri is not in the list of allowed callback URLs.
Please go to the Application Settings page and make sure you are sending a valid callback url from your application.
which sounds logical, because the return URL must be whitelisted.
The reason I want to do this is because I want the Sitecore container to be accessible to the outside world, for example by using a local tunnel with the tool localtunnel as follows:
lt --local-host xmcloudserge.loca.lt --port 443 --allow-invalid-cert --local-https -s xmcloudserge
Which should result in the URL https://xmcloudserge.loca.lt mapped to the same URL on my local machine.
Any ideas to accomplish this are greatly appreciated...
| |
As per my findings, this shows you the images from the system on the basis of some criteria. It doesn't mean that it will get removed if you clear the cache.
So to clarify it more, when you try to add an image in the image field, you can choose the image based on some criteria given on the left side of the Select Media dialogue like below.
Now if you go to the core database, you will get to know from where these criteria are defined. So go to the core database and on this location
/sitecore/client/Applications/Dialogs/SelectMediaDialog/PageSettings/SearchConfigs
you will get all the SearchConfigs that it is using to filter out the results. And on each config you will get some criteria.
Like for the "Recently Uploaded Images", you will see that it has a field checked called "CreatedWithin7Days" that shows you the images those were created with in 7 days.
If you uncheck this, you will see the filter will not work and you will get all the images when you click on the Recently Uploaded Images option.
So for each of the criteria on the left, there is a SearchConfig define in the core database and if you want to extend the functionality of any of these configs then you need to extend the pipeline that is holding this functionality.
Hope this makes sense.
| When an image is uploaded to the Media Library, how long does that image stay on the Recently Updated Images list before it falls off the list?
I think the answer is “it stays recent until the media cache is clear”. However, I am not 100% sure that is the best answer.
| |
The problem was that I didn't update the SQL db connection details for the folders I moved in:
\wwwroot\bootstrap\Global.json
\wwwroot\data\Environments\Plugin.SQL.PolicySet-1.0.0.json
| Sitecore Commerce Authoring does not start
I am trying to install the Sitecore Commerce 9.2 solution locally by porting wwwroot folders, databases, certificates from a server where it works fine on and installing them on top of my clean instance. I have a problem with my commerce authoring role. When bizfix or web interface try to address it the requests are pending and there's no response.
If I go to CommerceAuthoring folder and try to launch Sitecore.Commerce.Engine.exe I get Loading entity from file:C:\inetpub\wwwroot\CommerceAuthoring\wwwroot\Bootstrap\Global.json message and it does not progress further. There are no logs generated for CommerceAuthoring instance as well at C:\inetpub\wwwroot\CommerceAuthoring\wwwroot\logs.
The names in config files, thumbprints, iis bindings and certificates seem to be all correct for the instance. Do you maybe have an advice on what else I might check/try to launch it?
| |
xdt:Transform="RemoveAttributes(role:require)" should work correctly. But you need to remember to add xmlns:role="http://www.sitecore.net/xmlconfig/role/" attribute to the <configuration> tag of your tranform config file:
<configuration xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<databases>
<database xdt:Transform="RemoveAttributes(role:require)" />
</databases>
</configuration>
| How to use xdt transform to remove role:require attribute
I am using xdt transforms to modify my Sitecore.config file for different environments.
I want to remove a role:require="!ContentDelivery" attribute.
I'm targeting the following element:
<databases>
<!-- core -->
<database id="core" singleInstance="true" type="Sitecore.Data.DefaultDatabase, Sitecore.Kernel" role:require="!ContentDelivery">
and want to remove the role:require="!ContentDelivery" attribute.
If I use the following xdt syntax
<database id="core" singleInstance="true" type="Sitecore.Data.DefaultDatabase, Sitecore.Kernel" xdt:Locator="Match(id)" xdt:Transform="RemoveAttributes(role:require)"/>
I get the error "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.".
If I omit the namespace prefix i.e.
<database id="core" singleInstance="true" type="Sitecore.Data.DefaultDatabase, Sitecore.Kernel" xdt:Locator="Match(id)" xdt:Transform="RemoveAttributes(require)"/>
It doesn't work.
Is there a solution to this, or perhaps a better way to solve the problem?
| |
Dean OBrien's answer was helpful as a starting point when investigating this one. However I needed to dig deeper, which meant following the stacktrace and digging into the decompiled code which lead me to Sitecore.ExperienceAnalytics.Api.Query.QueryBuilder.FactsQueryBuilder.
This builder is actually building up the SQL query based on item configuration in /sitecore/system/Marketing Control Panel/Experience Analytics/Dimensions.
Here we can see that this item in question does not have the 'Converted' metric specified and hence causing the SQL error.
So we can simply delete everything out of /sitecore/system/Marketing Control Panel/Experience Analytics/Dimensions by adding a new version to that item and then deleting the item. Sitecore will delete all the items out the DB and then restore the stock items from the master resource file. After this, restart the CM server to clear all caches.
| Experience Analytics Error throwing System.Data.DataException error
I am in the upgrading process of Sitecore instance from 9.1 to 10.2 where the upgrade steps have been followed where I created a fresh 10.2.x instance and deployed the solution in to after the fact it got refactored to the version it is about to be deployed with. Except the data exception on Experience Analytics end.
ERROR [Experience Analytics]: System.Exception: Invalid column name 'Converted'. ---> System.Data.DataException: Error executing SQL command:
WITH WorkingSubset AS
(
SELECT Fact_ChannelTypeMetrics.[bounces], Fact_ChannelTypeMetrics.[conversions], Fact_ChannelTypeMetrics.[pageViews], Fact_ChannelTypeMetrics.[timeOnSite], Fact_ChannelTypeMetrics.[value], Fact_ChannelTypeMetrics.[visits], Fact_ChannelTypeMetrics.[outcomeOccurrences], Fact_ChannelTypeMetrics.[monetaryValue], Fact_ChannelTypeMetrics.[DimensionKeyId], Fact_ChannelTypeMetrics.[SegmentId], Fact_ChannelTypeMetrics.[Date],Fact_SystemMetrics.[totalVisits], Fact_SystemMetrics.[totalTimeOnSite], Fact_SystemMetrics.[totalPageviews], Fact_SystemMetrics.[totalEngagementValue]
FROM Fact_ChannelTypeMetrics INNER JOIN [DimensionKeys] on [DimensionKeys].DimensionKeyId = Fact_ChannelTypeMetrics.DimensionKeyId LEFT OUTER JOIN (SELECT * FROM Fact_SystemMetrics WHERE [SegmentId] IN (@systemSegmentId1)) AS Fact_SystemMetrics ON Fact_ChannelTypeMetrics.[SiteNameId] = Fact_SystemMetrics.[SiteNameId] AND Fact_ChannelTypeMetrics.[Date] = Fact_SystemMetrics.[Date] AND Fact_ChannelTypeMetrics.[FilterId] = Fact_SystemMetrics.[FilterId]
WHERE Fact_ChannelTypeMetrics.[SegmentId] = @SegmentId AND Fact_ChannelTypeMetrics.[Date] BETWEEN @StartDate AND @EndDate AND ((Fact_ChannelTypeMetrics.DimensionKeyId = @DimensionKeyId))
)
,BaseResults AS
(
SELECT Sum(CAST([bounces] as bigint)) AS [bounces], Sum(CAST([conversions] as bigint)) AS [conversions], Sum(CAST([pageViews] as bigint)) AS [pageViews], Sum(CAST([timeOnSite] as bigint)) AS [timeOnSite], Sum(CAST([value] as bigint)) AS [value], Sum(CAST([visits] as bigint)) AS [visits], Sum(CAST([outcomeOccurrences] as bigint)) AS [outcomeOccurrences], Sum([monetaryValue]) AS [monetaryValue], Sum(CAST([totalVisits] as bigint)) AS [totalVisits], Sum(CAST([totalTimeOnSite] as bigint)) AS [totalTimeOnSite], Sum(CAST([totalPageviews] as bigint)) AS [totalPageviews], Sum(CAST([totalEngagementValue] as bigint)) AS [totalEngagementValue], COUNT(*) OVER () AS [TotalDbRows]
FROM [WorkingSubset]
)
SELECT *, 1.0*TimeOnSite/Visits as [avgVisitDuration], 1.0*Bounces/Visits as [bounceRate], 1.0*Converted/Visits as [conversionRate], 1.0*PageViews/Visits as [avgVisitPageViews], 1.0*Value/Visits as [valuePerVisit], 1.0*MonetaryValue/Visits as [avgMonetaryValue]
FROM [BaseResults] ---> System.Data.SqlClient.SqlException: Invalid column name 'Converted'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Sitecore.Data.DataProviders.Sql.DataProviderCommand.ExecuteReader()
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at Sitecore.Data.DataProviders.Sql.DataProviderCommand.ExecuteReader()
at Sitecore.Data.DataProviders.Sql.DataProviderReader..ctor(DataProviderCommand command)
at Sitecore.Data.DataProviders.Sql.SqlDataApi.<>c__DisplayClass29_0.<CreateReader>b__0()
at Sitecore.Data.DataProviders.NullRetryer.Execute[T](Func`1 action, Action recover)
at Sitecore.Data.DataProviders.Sql.SqlDataApi.CreateReader(String sql, Object[] parameters)
at Sitecore.Analytics.Reporting.SqlReportDataSource.GetData(ReportDataQuery query)
at Sitecore.Xdb.Reporting.ReportDataProvider.ExecuteQueryWithCache(ReportDataQuery query, ReportDataSource dataSource, CachingPolicy cachingPolicy)
at Sitecore.Xdb.Reporting.ReportDataProvider.GetData(String dataSourceName, ReportDataQuery query, CachingPolicy cachingPolicy)
at Sitecore.ExperienceAnalytics.Api.ReportDataService.ExecuteQuery(IReportQueryData queryData, CachingPolicy cachingPolicy)
at Sitecore.ExperienceAnalytics.Api.ReportingService.RunQuery(ReportQuery reportQuery)
at Sitecore.ExperienceAnalytics.Api.Http.AnalyticsDataController.Get(ReportQuery reportQuery)
I have validated the following
XConnect app_data had infacts a valid license xml file
Users been added to the computer management Performance log users and Performance montior users
validated that the cert assigned is infact self-assigned
Performed a Sitecore 10.2.1 rev. 008245 PRE (OnPrem) Cumulative hotfix patch
Being a fresh xconnect instance rather with fresh dbs no old databases were reference to perform any xp related upgrades where as master db related upgrades like sql scripts, clean ups where done
Please let me know if i have missed any.
| |
If you will see the implementation of the method called this.GetText(), that you are using under your custom validation logic, it looks like this.
protected virtual string GetText(string text, params string[] arguments)
{
Assert.ArgumentNotNull((object) text, nameof (text));
Assert.ArgumentNotNull((object) arguments, nameof (arguments));
string str = string.Empty;
Database database = Context.Database;
if (database == null && this.ItemUri != (ItemUri) null)
database = Factory.GetDatabase(this.ItemUri.DatabaseName, false);
Item obj = database == null ? (Item) null : database.GetItem(this.ValidatorID);
if (obj != null)
str = obj[StandardValidator.textFieldId];
if (string.IsNullOrEmpty(str))
str = this.Parameters["Text"];
if (!string.IsNullOrEmpty(str))
text = str;
return Translate.Text(text, (object[]) arguments);
}
So it first checks for the ValidatorID variable using this.
Item obj = database == null ? (Item) null : database.GetItem(this.ValidatorID)
If it gets the Item, then it checks for the textFieldId and i.e. this
private static readonly ID textFieldId = new ID("{5DCF6FF3-41C5-466C-AD5E-991CFCD55716}");
If you see this field in the CMS, you will see that this is the ID for the field that you are looking for. Here is the screenshot.
And if this field is blank then it does the further operations.
So I think you need to pass the value in this.ValidatorID variable and it should get the value of the text field that you want to use.
Hope this makes sense.
| How do you get and display the Validation Rule Text field?
I'm currently implementing a custom validation logic, and I'm planning to leverage the existing fields of the Validation Rule template such as the Text field to be used as an error message. Is this possible? if yes how do you get the values?
| |
PowerShell is a great choice for dealing with Sitecore items. Assume that you already have your somescript.ps1 script ready and want to run it from a Gulp task while building & deploying your project files. The below script will help you to achieve this:
gulp.task('your-task', function (cb) {
var psScriptPath = "your-script-path";
exec('powershell.exe -file ' + psScriptPath + 'somescript.ps1', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
| Run PowerShell script using Gulp?
Is there any way to run a PowerShell script in Sitecore using Gulp? We are trying to integrate some content publishing to the build process automatically. All our JS/CSS is stored in the Media Library which needs to be manually published each time there is a new build so we want to automate this task.
| |
You can use below code, in which {0729C93B-888A-4765-8486-8F1AE86A3894} is orkflow state id.
$itemsWithMatchingDefaultWorkflow = Get-Item -Path master: -Query "/sitecore/content/*[@__Workflow='{0729C93B-888A-4765-8486-8F1AE86A3894}']"
foreach ($item in $itemsWithMatchingDefaultWorkflow)
{
Write-Host " -" $item.ID $item.Paths.FullPath
}
Or you can use this as well -
Get-ChildItem -Path master:\sitecore\content -Recurse | Where-Object { $_.__Workflow -eq "{0729C93B-888A-4765-8486-8F1AE86A3894}"}
And to update you can use below -
$rootItem = Get-Item -Path master:"START PATH"
$language = "en"
$workflowFinalState = "WORKFLOW STATE GUID"
foreach ( $item in Get-ChildItem -Item $rootItem -Recurse -Language $language)
{
$item.Editing.BeginEdit();
$item.Fields["__Workflow state"].Value = $workflowFinalState
$item.Editing.EndEdit();
Write-Host "$($item.FullPath) --> Updated"
}
Or you can use this as well to update workflow -
$itemsWithMatchingDefaultWorkflow = Get-ChildItem -Path master:\sitecore\content -Recurse | Where-Object { $_.__Workflow -eq "Workflow state id"}
foreach ($item in $itemsWithMatchingDefaultWorkflow)
{
$item.__Workflow = "Workflow final state id"
}
| How to fetch items that have not completed workflow, using powershell script
Using sitecore 10.0.1
Currently, I want to move items under a path, to "Approve" workflow. So how to fetch items that are not in approved state and change them to "Approved" workflow using powershell script
| |
For performance reasons, Sitecore does not explicitly read item fields that have no value, or fields that have only Standard Value defined, that is why you may not see them in the collection Context.Item.Fields.
You can use one of the following options to read the required field:
change your code to Context.Item[BaseConstants.CheckboxOneFieldId]
or call the method Context.Item.Fields.ReadAll() before accessing the collection of fields
You can find more details about this behaviour in the post When is item.Fields.ReadAll() required to be run?
| Standard value field in template not reflecting in Context.Item
I have an existing template, Template E. This template inherits a base template, Template B. Template B has two checkbox fields. In Template E's standard value, I have checked the inherited checkbox fields and published the same. Now all the existing items referring to Template E has those two checkbox fields checked. I have a custom tracking pipeline <mvc.requestEnd> which checks this checkbox fields. Now the problem is the Context.Item is not picking the standard value fields and I am unable to see the CheckboxOne field in Context.Item.Fields.
Sample config:
<sitecore>
<pipelines>
<mvc.requestEnd>
<processor type="Myproject.GoogleAnalytics, MyProject"/>
</mvc.requestEnd>
</pipelines>
</sitecore>
Sample code:
namespace MyProject
{
public class GoogleAnalytics : MvcPipelineProcessor<RequestEndArgs>
{
public override void Process(RequestEndArgs args)
{
try
{
if (Context.Item != null && Context.Item.Paths.IsContentItem)
{
if (Context.Item.Fields[BaseConstants.CheckboxOneFieldId] != null &&
Context.Item.Fields[BaseConstants.CheckboxOneFieldId].HasValue &&
Context.Item.Fields[BaseConstants.CheckboxOneFieldId].Value.Equals("1"))
{
//Logic to implement
}
}
}
catch(Exception ex)
{
}
}
}
}
Is this a Sitecore bug? I am using Sitecore 8.2.
| |
XDB can not be disabled for a specific site in a multisite setup either it is on for all or off for all.
| Disable xDB in Multisite Website
Can we enable xDB for a specific website and disable it for other? I know we have this option for xdb tracking but what about Xdb.Enabled? can this setting be true/ false for a specific site?
| |
In short: That article is a bit outdated and is not applicable to recent 10.x containerised solutions. The “production entrypoint” is now defined in each role’s base image and made publicly available via the Sitecore Container Registry. These entry points are the default unless specifically overwritten. This is not necessarily Production.ps1, but executes the appropriate commands to run that role (similar to what is outlined in that article). Hence you won’t find Production.ps1 in those images, nor should it be required to spin up the containers.
Development.ps1 is present as your image build will be copying in the Sitecore docker tool assets. Around the time v10 was released the Sitecore docker tool assets (https://github.com/Sitecore/docker-tools) were moved to their own image hosted in the Sitecore Container Registry (scr.sitecore.com/tools/) and the “production entry points” were baked into the base role images that Sitecore began providing in the SCR. The tools assets became focussed on developer experience, while the default base images focussed on production readiness.
Prior to this (i.e. <= v9.3), all images had to be built from scratch (ie. base images are not provided in the SCR) and thus the sitecore-assets (including the tools) were included in the version specific build folders of the docker-images repo (e.g. https://github.com/Sitecore/docker-images/tree/master/build/windows/9.3.0/sitecore-assets/tools/entrypoints/iis) which gives a starting point to build these images. Here you can see the Production.ps1 script.
Of course, you can still override any of the entry points in your dockerfile or docker-compose if required, the production.ps1 is just no longer part of the tools assets.
| Where is Production.ps1 script in Sitecore docker images?
This document https://www.sitecore.com/knowledge-center/getting-started/docker-entrypoints
describes two PowerShell scripts used as ETRYPOINT, named Production.ps1 and Development.ps1.
They should be present in the containers based on the Sitecore 10 Docker CD image. While Development.ps1 exists after the image build process, the first file is missing from the indicated folder: C:\tools\entrypoints\iis.
I have verified that the images are "production ready", and they are. I contacted Sitecore but they didn't answer me. Some idea?
| |
You can go through this link - https://www.nishtech.com/Blog/2020/April/Advanced-content-packaging-with-Powershell
Step 1 - Use Powershell Reports to get the modified items CSV file
To find the Powershell Reports, open the Sitecore in Desktop Mode, then click at the Reporting Tools menu item, as shown in the image below.
In our example, we are using the “Items last updated after date“ report. In the configuration pop-up, select the Report Root in the content tree, and the After Date and Time.
Since we are deploying our Sprint content, we will input the date when the Sprint actually started, so the resulting list will only include the items modified during the sprint.
The reporting results can be conveniently browsed and reviewed. Double-clicking a row will pop-up the item in Content Editor.
Go ahead and download the CSV file by clicking in the highlighted icon.
Step 2 - Open and Review in Excel
The CSV file generated in the last step can now be opened in Excel, enabling your team to easily review and modify the file by using Excel features such as Sort and Filter.
Your team can be consulted to confirm which of their items are supposed to be included in the package, and what should not be there. For that, you can use the “Updated by“ column to identify the user who modified the items.
Feel free to modify the file as you want, removing the lines that should not be included. As long as the column names are kept, and you have no empty rows, it should be good.
Step 3 - Convert the CSV file into a Sitecore Package
Now that your spreadsheet is properly revised and adjusted, we will use it to generate the Sitecore Package with the items present in your CSV file.
For that, you will need the following Custom Powershell Script - Create Package from Report CSV file.ps1
Powershell Script itself
or
Sitecore Package for quick installation
If you either install the package above or manually create the script under the path /sitecore/system/Modules/PowerShell/Script Library/Package Generator/Toolbox, you will then be able to trigger this script from the Powershell Toolbox.
The script will prompt the user to upload the revised CSV file.
After finished, the user is prompted to download the generated package
Step 4 - Install the package
When the time comes, use the Sitecore Installation Wizard to install the package - don’t forget to trigger a publish when the installation finishes!
| How to take item package of particular time period using Sitecore Powershell?
We are working on Sitecore Upgrade and would like to merge the item changes for the particular period.
If we try to use item dynamic package, it is taking longer time and timed out somewhere.
Is there any way to take by using Sitecore powershell and if the item count is more, we have to split up as separate packages.
| |
Leprechaun is an open API code generator from Sitecore Content Serialized or from Unicorn serialized items. The leprechaun can be run at build-time with a pre-build step or with CLI.
Leprechaun uses state-of-the-art Roslyn code generation technology instead of T4 templates for a speedy generation that doesn't require Visual Studio.
Why should I use Leprechaun?
It's Really Flexible
Leprechaun uses C# Script files as templates. If you're familiar with C#, it's a breeze. Out of the box, a Synthesis script file is provided, but it can easily be adapted to generate templates Glass, Fortis, or more! The template is essentially a big StringBuilder that you can build out however you like and Leprechaun will fill in the rest.
It Can Be Run at Build-Time
Sick of trying to resolve merge conflicts in gigantic model files? You don't need to do that anymore with Leprechaun. The outputted model files don't have to be checked into source control at all!
Why not?
Leprechaun generates models based off of the yaml files outputted by Rainbow. Since these yaml files are on disk already, there's no need for Sitecore to be running or for Visual Studio to be open in order to generate the models. Without these dependencies, you can generate models as a pre-build step.
It's Helix-Friendly
Most everything in Leprechaun is config-based. The base Leprechaun.config (for Rainbow, for Sitecore Serialization) file contains everything needed for Leprechaun to get started for a single project. However, these configs can be extended and overridden. For each module you have, create a CodeGen.config file and have it extend another config.
It’s a Helix-friendly code generator which was really important during the upgrade.
So yes it is good to use as it is Sitecore friendly.
For the git repo, you can visit here - https://github.com/blipson89/Leprechaun
| Code generation in Sitecore 10.2 apart from TDS
Recently we have upgraded Sitecore to 10.2. For code generation we have implemented 'Leprechaun' and code is being generated fine. But I want to know if 'Leprechaun' is recommended by Sitecore. If no, then what is the preferred way of code/model generation apart from TDS in Sitecore 10.2? and if there is any video or article available for the same. Can anyone please help me with that?
| |
This error message is being generated by the ShutdownMonitor which is the manager that listens for Web App shutdown commands. When the webapp receives an instruction for shutting down, this monitor fires the Stop() method, which writes this error message.
Essentially, what's happening is that the Azure WebApp Service is attempting to do something that is about to cause the web application to recycle. As a result, this stop method is going to interrupt any indexing that is going on.
An Azure Webapp service can recycle for any number of reasons, some common ones are as follows:
WebApp Service Host is being rebooted by Microsoft for Updates
Enough Application Errors bubbled to the top of the WebApp stack to cause the AppService to recycle (this is the most common reason for WebApp reboots)
A deployment occurred which will also recycle the AppService.
The indexing process can not ignore this request, because there are clean up actions that have to quickly be taken care of before the WebApp Service is rebooted. So the process ends all indexes, to allow for a safe WebApp Service reboot.
| Hosting Environment Stop Requested... why?
At unexpected moments, we find this message in our Sitecore log: Hosting Environment Stop Requested : immediate=False
What is the best way to find out why this is happening?
It would be very useful if this log message was accompanied by the reason for the "request", but unfortunately it isn't. (And in our case, I think there's nothing going on with idle timeouts or changes in the file system.)
| |
I found the below lines in the Sitecore document:
To achieve this, I followed below link:
https://sitecore.marcelgruber.ca/posts/storing-full-urls-in-page-view-events
| Page Event is not saving into xDB
I want to save some information about that page that has been clicked by the user so I register a page event on processItem pipeline for this I did below code:
public class RegisterCustomPageEvents : ProcessItemProcessor
{
public override void Process(ProcessItemArgs args)
{
foreach (TrackingField trackingParameter in (IEnumerable<TrackingField>)args.TrackingParameters)
TrackingFieldProcessor.ProcessEvents(args.Interaction, trackingParameter);
if (!Tracker.Enabled || Tracker.Current == null || !Tracker.Current.IsActive)
{
return;
}
FireCustomEvent(args);
}
private void FireCustomEvent(ProcessItemArgs args)
{
var myPageTemplateId = "{ED0B99D5-4992-429F-84FE-F8F3D902CAB5}";
if (args.Item == null || Context.Item.TemplateID.ToString() != myPageTemplateId)
{
return;
}
var ev = Tracker.MarketingDefinitions.PageEvents[Guid.Parse("{059A1829-DD32-47B6-8EA6-BEEFAC98DC6E}")];
if (ev != null)
{
var pageData = new PageEventData(ev.Alias, ev.Id);
pageData.Text = "Event";
var fullUrl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
pageData.CustomValues.Add("Url", fullUrl);
pageData.CustomValues.Add("PageTemplateId", args.Item.TemplateID.ToString());
pageData.CustomValues.Add("ItemVersion", args.Item.Version.Number);
pageData.ItemId = args.Item.ID.ToGuid();
try
{
Tracker.Current.CurrentPage.Register(pageData);
}
catch (Exception ex)
{
Log.Error("Unable to fire custom event", ex, this);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<processItem>
<processor type="XXX.RegisterCustomPageEvents, XXX" />
</processItem>
</pipelines>
</sitecore>
</configuration>
My issue is that I am not able to see page events in Interactions table. I tried to abandon the session.
| |
Adding up to Anna's answer After Investigation by our principal we sent a support ticket to sitecore regarding the issue to confirm the right action to be taken
we confirmed with sitecore support the issue and it truly was regarding item versions that doesn't contain a language, they said
"It is likely possible that another record for same item id/field id combination exist in this table."
they suggested to do a clean up for such unwanted fields using the following query against master db
delete from [VersionedFields] where Language = ''
this sorted out the issue for us and the workbox worked again without any issues.
They also added "Such issue can happen when items packaged from an environment are installed in another environment where language does not exists. So, if these fields are necessary, you can create necessary language item before installing any such package."
| Can't select certain workflow in workbox
I'm facing an issue on selecting certain workflow in workbox
Edit 1: the workflow that has the issue is the one in the select box that has black label , approval workflow - generic.
Sitecore 10.1.0
steps taken to resolve issue,
check item name validation configuration.
https://stackoverflow.com/questions/23931721/sitecore-workbox-empty-string-is-not-allowed-error
push all items in that workflow to a final state using powershell script, In case content is the issue.
make sure according to relevant answer here that default comment template has a value
https://stackoverflow.com/questions/37201210/sitecore-server-error-in-application-empty-strings-are-not-allowed-param
tried all the above fixes,however issue still persists, If anyone has any info regarding this issue, please share with us, thank you.
Edit 2 :
Also extra check has been made to make sure workflow item that has the issue and all children items under it like commands, action items, has only 1 language (English by default) and only 1 version
detailed exception can be found below
Server Error in '/' Application.
Empty string is not allowed.
Parameter name: value.
Actual value was .
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.ArgumentOutOfRangeException: Empty string is not allowed.
Parameter name: value.
Actual value was .
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:
[ArgumentOutOfRangeException: Empty string is not allowed.
Parameter name: value.
Actual value was .]
Sitecore.Diagnostics.Error.AssertString(String argument, String name, Boolean allowEmpty) +172
Sitecore.Shell.Framework.CommandBuilders.CommandBuilder.Add(String key, String value) +64
Sitecore.Shell.Applications.Workbox.WorkboxForm.CreateCommand(IWorkflow workflow, WorkflowCommand command, Item item, XmlControl workboxItem) +443
Sitecore.Shell.Applications.Workbox.WorkboxForm.CreateItem(IWorkflow workflow, Item item, Control control) +2747
Sitecore.Shell.Applications.Workbox.WorkboxForm.DisplayState(IWorkflow workflow, WorkflowState state, StateItems stateItems, Control control, Int32 offset, Int32 pageSize) +267
Sitecore.Shell.Applications.Workbox.WorkboxForm.DisplayStates(IWorkflow workflow, XmlControl placeholder) +1300
Sitecore.Shell.Applications.Workbox.WorkboxForm.DisplayWorkflow(IWorkflow workflow) +660
Sitecore.Shell.Applications.Workbox.WorkboxForm.Pane_Toggle(String id) +229
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +132
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +146
Sitecore.Shell.Framework.Commands.MethodCommandProcessor.Invoke(PipelineArgs args) +461
Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) +348
Sitecore.Pipelines.Pipeline.Start(PipelineArgs args, Boolean atomic) +167
Sitecore.Shell.Framework.Commands.MethodCommand.Execute(CommandContext context) +621
Sitecore.Web.UI.Sheer.ClientPage.Dispatch(String command) +231
Sitecore.Web.UI.Sheer.ClientPage.RaiseEvent() +124
Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e) +795
System.Web.UI.Control.PreRenderRecursiveInternal() +200
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7479
| |
You can use {{i_datasource.Image}} or {{ i_item.Image}} to get image src and alt. Here .Image is the image type field name, in your case, it seems like Thumbnail. so, it should be {{i_datasource.Thumbnail}}
Scriban code should be something like this:
<div class="some-class">
{{i_datasource.Image}}
</div>
The output will be:
<div class="some-class">
<img src="/-/media/Project/Sites/image-name.png" alt="image-alt">
</div>
Refer to this documentation for more details: https://doc.sitecore.com/xp/en/developers/sxa/102/sitecore-experience-accelerator/scriban-templates.html
| How to get 'Alt' field value of Sitecore media item by Sitecore Scriban embedded method?
I am able to get the Sitecore media link by using the Sitecore Scriban Embedded method as follows:
<img src="{{sc_follow i_article 'Thumbnail'| sc_medialink}}">
But, not sure how to get the value of the Alt field value of the Sitecore Media item using the Sitecore Scriban Embedded functions.
| |
You can register a custom route to a regular sitecorecontroller using:
RouteTable.Routes.MapRoute( "yourcustomroute", "custom/path", new { controller = "yourcontroller", action = "youraction" } );
Then call that via an ajax call.
By doing it this way, it is like navigating to that page in the normal session and sitecore tracker is available.
This article covers the main points involved in setting this up:
https://www.mydatahack.com/how-to-configure-custom-goals-and-trigger-them-by-ajax-call-sitecore/
| Save Contact on API call
Here is my scenario - on the page, there will be a button, on the button click there will be a popup and the user will enter some detail. On submit button, I need to create a contact and save custom facets on xDB and after that, there will be a confirmation message on the same popup.
Because I do not want to post back the page, I am doing an ajax call, and Tracker will not be available on ServicesApiController. Is there any solution to this?
Code:
public class SubscriptionApiController : ServicesApiController
{
private readonly IContactRepository _contactRepository;
public SubscriptionApiController()
{
_contactRepository = ServiceLocator.ServiceProvider.GetService<IContactRepository>();
}
[HttpPost]
public HttpResponseMessage Post(SubscriptonModel model)
{
try
{
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Constants.ErrorMessage.InternalServerError);
}
}
}
Route
public class WebApiServices
{
public void Process(PipelineArgs args)
{
GlobalConfiguration.Configure(Configure);
}
protected void Configure(HttpConfiguration configuration)
{
var routes = configuration.Routes;
routes.MapHttpRoute("subscriptionApi", "api/{controller}/{action}", new { });
}
}
| |
I think this is expected behavior as the field name will get directly served as a property on the javascript side which would not work with spaces in the middle of it.
What you can do as a workaround is to name your Sitecore field PageTitle and then set its Title field (under Data section) to be Page Title - this way your content editors will see a more readable version when they work with an item of this template and field reference will work too.
| unable to use space in field name like "Page Title" in sitecore with nextjs
I'm unable to use space in field name like "Page Title" in sitecore with nextjs.
in Layout.tsx it works like below but not working when have sitecore filed
like "Page Title":
const { route } = layoutData.sitecore;
return (
<>
<Head>
<title>{route?.fields?.PageTitle?.value || 'Page'}</title>
<link rel="icon" href={`${publicUrl}/favicon.ico`} />
</Head>
.
.
.
| |
Sitecore user (virtual or persistent) is created automatically when Federated Authentication processes the POST request from Auth0 back to Sitecore. If you want to ask users for additional information after the first login, I would recommend to store a custom flag in the Auth0 user profile that will help you identify whether current user completed the second step of registration or not. For example, you can store a boolean value in a field called "Registration Complete" and check its value to redirect the user appropriately.
Here is some additional information to answer your questions:
How to access Auth0 user profile fields in Sitecore?
The best way to do this is by mapping Auth0 claims to Sitecore user profile fields during login. Federated Authentication provides a standard way to do this with <propertyInitializer> config section. For example, this is how you can map the Email address claim in Sitecore config file:
<sitecore>
<federatedAuthentication>
<propertyInitializer type="Sitecore.Owin.Authentication.Services.PropertyInitializer, Sitecore.Owin.Authentication">
<maps hint="list">
<map name="Email claim" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication" resolve="true">
<data hint="raw:AddData">
<source name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
<target name="Email" />
</data>
</map>
</maps>
</propertyInitializer>
</federatedAuthentication>
</sitecore>
Then you will be able to access email of the logged-in user in your custom code using standard Sitecore API:
Sitecore.Context.User.Profile.Email
Why is the POST request from Auth0 followed by GET request?
This is expected behaviour. When Sitecore receives a POST request and sees OAuth 2.0 parameters in the request body, it tries to find an Identity Provider Processor for the current website and call notification handlers from the found processor. After this, Sitecore will authenticate the user and redirect him via GET request to the redirectUrl that was sent in the original https://YOUR_DOMAIN.auth0.com/authorize request.
So the user is not authenticated until Sitecore processes the first POST request, but he will be in the next GET request. This is why you get a redirect loop after adding [Authorize] attribute to the method LoginWithRole - it prevents Sitecore from running authentication process and instead redirects to the URL configured as loginPage in the site config.
Therefore, you should perform the custom logic that will check user profile fields and display the second step of registration only after Sitecore authentication is complete.
Please note that you will need to handle scenarios when users successfully logged in but did not complete the second step and went to another page instead. Depending the desired user experience, you may want to use a custom processor in <httpRequestBegin> pipeline to redirect users or choose to have a component that will prompt users to complete registration.
| Sitecore 10.2 Auth0 Login with post registration form: Cannot retrieve claims from User.Identity
I have integrated Auth0 as an Owin identity provider so that in the future I can manage website users via the Auth0 platform. After registration the user should be redirected to a form asking for some additional data (postal address, etc.), then a Sitecore user account should be created.
For the implementation I followed this project: Auth0 in Sitecore. I use the same processor class (Auth0IdentityProviderProcessor.cs), the same provider configuration (Auth0InSitecore.config) and also enabled federated authentication.
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore role:require="Standalone or ContentDelivery or ContentManagement">
<settings>
<setting name="Owin.Authentication.Enabled" value="true" />
<setting name="FederatedAuthentication.Enabled" value="true" />
</settings>
<services>
<register serviceType="Sitecore.Abstractions.BaseAuthenticationManager, Sitecore.Kernel"
implementationType="Sitecore.Owin.Authentication.Security.AuthenticationManager, Sitecore.Owin.Authentication"
lifetime="Singleton" />
<register serviceType="Sitecore.Abstractions.BaseTicketManager, Sitecore.Kernel"
implementationType="Sitecore.Owin.Authentication.Security.TicketManager, Sitecore.Owin.Authentication"
lifetime="Singleton" />
<register serviceType="Sitecore.Abstractions.BasePreviewManager, Sitecore.Kernel"
implementationType="Sitecore.Owin.Authentication.Publishing.PreviewManager, Sitecore.Owin.Authentication"
lifetime="Singleton" />
</services>
<sites>
<site name="shell" set:loginPage="/sitecore/login" role:require="Standalone or ContentManagement" />
<site name="admin" set:loginPage="/sitecore/admin/login.aspx" />
</sites>
</sitecore>
</configuration>
Of course I added the Auth0 credentials (client ID, redirect URI, etc.) and set the URLs (callback URL, logout URL) in my Auth0 development account. The callback URL would be https://mypage.de/Web/Account/LoginWithRole (I test on my local computer with an IIS site).
My account controller looks like this:
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Sitecore;
using Sitecore.Links;
using Sitecore.Security.Authentication;
namespace Controllers
{
public class AccountController : AreaController
{
public ActionResult Login()
{
HttpContext
.GetOwinContext()
.Authentication
.Challenge(new AuthenticationProperties
{
RedirectUri = Url.Action("LoginWithRole", "Account", new { area = "" })
},
"Auth0"
);
return new HttpUnauthorizedResult();
}
public ActionResult LoginWithRole()
{
var claimsIdentity = User.Identity as ClaimsIdentity;
var eMail = claimsIdentity?.FindFirst(c => c.Type == ClaimTypes.Email)?.Value;
return Content(""); // only for testing
}
}
}
So, the login action method works as expected. Auth0 opens and I can register a new user via login form. When I go into SecurityTokenReceived handler (Auth0 processor) with debugger I can also see my data (name, access token, etc.).
But the data is not accessible in LoginWithRole action method. I would like to get the Auth0 claims from User.Identity.
In the network panel of the browser developer console, I could see that Auth0 makes a POST request to https://mypage.de/Web/Account/LoginWithRole, but the program flow does not go into the method (I checked this while debugging). Instead, another redirect is made to the same URL using the GET method. Then the program flow goes into the method body, but the User.Identity property points to a Sitecore user object.
When I add attributes like Authorize or HttpPost to my action method, I get into a redirect loop (Login > LoginWithRole as POST > Login > etc.). I do not know why.
Maybe someone has had the same (or similar) problem before and knows how to solve it? Any suggestion would be really helpful.
Thanks in advance.
| |
As discussed in the comments, there is no need to add the "_sm" in ContentTypeSearchResultItem.
In your latest update, it looks like you are trying to map a stringcollection to an IEnumerable < Guid >
Please can you try changing index config to:
<field fieldName="content_type" returnType="guidCollection"></field>
And then update your SearchResult to:
[Sitecore.ContentSearch.IndexField("content_type")]
[TypeConverter(typeof(IndexFieldEnumerableConverter))]
public IEnumerable<Guid> ContentType { get; set; }
You will need to repopulate and rebuild the index.
| ERROR Solr Error : [undefined field content_type] - upgarding from Sitecore 8.2 to 10.1 and from Lucene to Solr
I'm working on a Sitecore upgrade from 8.2 to 10.1, which includes replacing Lucene with Solr. I have a content listing page that allows filtering by content type as well as many other fields - these are OOTB Sitecore fields, not computed. I have this SearchResultItem defined:
public class ContentTypeSearchResultItem : Sitecore.ContentSearch.SearchTypes.SearchResultItem
{
[Sitecore.ContentSearch.IndexField("region_sm")]
[TypeConverter(typeof(IndexFieldEnumerableConverter))]
public Guid Region { get; set; }
[Sitecore.ContentSearch.IndexField("content_type_sm")]
[TypeConverter(typeof(IndexFieldEnumerableConverter))]
public IEnumerable<Guid> ContentType { get; set; }
}
One thing I changed initially was that the names had no suffixes, so I changed "content_type" to "content_type_sm" (this was after I got the Undefined error the first time)
My fields exist in Solr:
and in fact in another place in the site where I pull all items with a particular template ID, when I inspect the items while debugging, I can drill into the fields and see that they have the "content_type_sm" field and it is properly populated.
But on the listing page, my query which uses this code:
var contentTypePredicate = PredicateBuilder.True<ContentTypeSearchResultItem>();
foreach (var taxonomy in taxonomies)
{
contentTypePredicate = contentTypePredicate.Or(x => x.ContentType.Contains(taxonomy));
}
predicate = predicate.And(contentTypePredicate);
...returns no results and I see the error in my logs, ERROR Solr Error : [undefined field content_type]
EDIT:
Manually updating the fieldMap fixed the issue:
<field fieldName="content_type" returnType="stringCollection"></field>
| |
In Sitecore 8.2, there was a custom LinkList DataHandler that was registered in GlassMapperScCustom.cs file.
dependencyResolver.DataMapperFactory.Insert(0, () => new LinkListDataHandler());
We added the same in the Sitecore 10.2 instance and it worked.
| Glass Mapper mapping exception for a LinkList field after upgrade to Sitecore 10.2
We are upgrading our Sitecore instance from Sitecore 8.2 version to Sitecore 10.2 version, ORM used in Sitecore 8.2 is GlassMapper(v4.3.4.197).
We have upgraded glass mapper in Sitecore 10.2 via NuGet package manager.
In Sitecore 8.2 there was a custom field called Linked List which is working fine with Glass Mapper, but after upgrading to Sitecore 10.2, this field is showing an error while mapping.
The current site utilizes a custom link list field as instructed in the URL: http://code.monoco.se/2012/12/a-shiny-new-field-type-linklist/
Model class for glass mapper:
public partial class Footer : GlassBase
{
[SitecoreField(IFooterConstants.LinksFieldName)]
public virtual IEnumerable<Link> Links { get; set; }
}
View File for rendering file:
@foreach (var link in Model.Links)
{
<li>
@Html.Glass().RenderLink(link, x => x)
</li>
}
Post upgrading the glass mapper.
we are getting the below exception for the link list field.
Glass.Mapper.MapperException: 'Failed to map field {51227AF0-F7B9-4930-8CF5-A4055FA69642} with value
<links><link text="About us" anchor="" linktype="internal" class="" title="About Us" target="" querystring=""
id="{B6B3EA62-37F4-4EB1-AD3B-33DEAFCFDCBA}" /><link text="Corporate responsibility" anchor="" linktype="internal" class=""
title="Corporate Responsibility" target="" querystring="" id="{AC469CBD-143E-458B-BFA9-10532835CCDD}" />
<link text="Diversity, equity and inclusion" anchor="" linktype="internal" class="" title="" target="" querystring=""
id="{0C437528-7C87-4F49-BEE1-4514A9A450BF}" /><links>
| |
There is a Scriban function called 'sc_getitem' that exists in SXA 10.0+ that should do what you want. It allows you to get the item by either path or id and will use the context language by default. You can change the language if you want and I included an example below.
{{~ itemId = "{2C7654E0-6EE0-490A-A964-00EF71E4CAF7}" ~}}
{{~ itemPath = "/sitecore/content/Home" ~}}
itemById = (sc_getitem itemId)
itemByPath = (sc_getitem itemPath)
itemByPathAndLang = (sc_getitem itemPath 'de-DE')
| Get Item by path or ID using Scriban in Sitecore
Environment: Sitecore 10.2 & SXA 10.2
Scenario: I would like to get the item by using its path or ID in Scriban.
Is there any OOTB functionality to achieve this?
| |
You would also need to configure the language on the frontend in the next.config.js file:
i18n: {
locales: ['en', 'da-DK'],
},
Here is the official documentation: https://doc.sitecore.com/xp/en/developers/hd/190/sitecore-headless-development/internationalization-in-the-jss-sample-app-for-next-js.html
| Multi Language not working in Sitecore headless
We are using Sitecore 10.2 as headless (JSS) and nextjs for the front end.
When we try to call JSS API it is working with multiple languages.
https://{Sitecore}/sitecore/api/layout/render/jss/?item={ItemID}&sc_apikey={apiKey}&sc_lang={langcode}
But from the front when we try to call, it is working only for EN, not working for other languages. Gives 404 when I try to access for a different language.
I guess we are missing something from the front end.
Please let me know if we are missing something.
| |
Ensure you have configured the following options using the Windows features-Turn Windows features on or off, and rerun the setup.
| Error while installing Sitecore 9.1: Service 'Sitecore XConnect Search Indexer' cannot be stopped
I am facing an error related to service 'Sitecore XConnect Search Indexer' while installing Sitecore 9.1.
| |
If you are happy to update the target path each time, then all you need to do is add a counter into your script, then check its less than 100 each time through the for loop.
$sourcePath = "/sitecore/media library/Default Website"
$targetPath = "/sitecore/media library/dev"
$counter = 0
Get-ChildItem $sourcePath -Recurse | ForEach-Object {
$name = $_.Name
if((![string]::IsNullOrEmpty($name)) -and ($counter -lt 100) -and ($_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder)))
{
Move-Item -Path $_.ItemPath -Destination $targetPath;
Write-Host "Item moved to: "$_.ItemPath;
$counter+=1
}
else
{
Write-Host "Couldn’t move Item because empty name: " $_.Id;
}
}
Note I also added in a check to confirm the templateId for the item is not a folder.
When testing out powershell scripts in sitecore, it is useful to first do a test run to see what would be effected without moving the items themselves.
The script below, splits the actions into two methods Find-MediaItems and Move-MediaItems. You can then call Find-MediaItems first and output the results to table.
If you are happy with what is going to be moved, you then need to uncomment the line #MoveItem($item), and comment out the line above.
function Find-MediaItems {
$items = Get-ChildItem -Path $sourcePath.Paths.FullPath |
Where-Object { ($_.TemplateID -ne [Sitecore.TemplateIDs]::MediaFolder) }
foreach($item in $items) {
$item;
#MoveItem($item)
}
}
function MoveItem($item)
{
$name=$item.Name
if((![string]::IsNullOrEmpty($name)) -and ($counter -lt 100)))
{
Move-Item -Path $_.ItemPath -Destination $targetPath;
Write-Host "Item moved to: "$_.ItemPath;
$counter+=1
}
else
{
Write-Host "Couldn’t move Item because empty name: " $_.Id;
}
}
$props = @{
InfoTitle = "Media items to move"
InfoDescription = "Lists all media items that the script will eventually move"
PageSize = 25
}
Find-MediaItems |
Show-ListView @props -Property @{Label="Name"; Expression={$_.DisplayName} },
@{Label="Updated"; Expression={$_.__Updated} },
@{Label="Updated by"; Expression={$_."__Updated by"} },
@{Label="Created"; Expression={$_.__Created} },
@{Label="Created by"; Expression={$_."__Created by"} },
@{Label="Path"; Expression={$_.ItemPath} }
Close-Window
The above is something I found myself when in similar situation to you, then have edited to suit over time (cant recall original source).
| Moving images to another folder Powershell
I am trying to move images from one folder to another. The images folder contains like 1000 images. i want to move the first 100 images to one folder the other 100 images to another folder and the other 100 images to another folder.
i found a script that moves all the images. but i need to move by 100.
even if i get the code for first 100 i can change the path in the code(target Path).
Thanks
$sourcePath = "/sitecore/media library/Default Website"
$targetPath = "/sitecore/media library/dev"
$optionalTemplateNameToMatch = ""
# optional template get children line
# Get-ChildItem $sourcePath -Recurse | Where-Object { $_.TemplateName -match $optionalTemplateNameToMatch } | ForEach-Object {
Get-ChildItem $sourcePath -Recurse | ForEach-Object {
$name = $_.Name
if(![string]::IsNullOrEmpty($name))
{
Move-Item -Path $_.ItemPath -Destination $targetPath;
Write-Host "Item moved to: "$_.ItemPath;
}
else
{
Write-Host "Couldn’t move Item because empty name: " $_.Id;
}
}
| |
Unfortunately, OOTB, it is not possible as whatever submit action you are using it is going to store its value in the Parameters field of Submit Action Definition item. So, for example, if you are using send email as your submit action it stores the value of the complete form value into the Parameters field in JSON format as below -
{"to":"[email protected]","from":"[email protected]","subject":"test","body":"<p>This is for testing </p>}
even if you want to use any image in the form builder it will not allow you to use it from Sitecore itself but from your local, you can attach a media which will convert into a base64 string and store it as JSON in the Parameters field. Although the user interface for email form builder is controlled from below file -
/sitecore/shell/client/Applications/FormsBuilder/Layouts/Renderings/RichTextEditor/RichTextEditor.cshtml
I think this is going to be very complex but you do something with this file by adding your custom button and writing your custom javascript to get the link values from Sitecore.
| Inserting the Sitecore media files as link in the email template of Sitecore forms
I am using Sitecore forms in Sitecore 10.2 but I don't see any option for making a downloadable link by attaching the Sitecore media files in the email template attached to submit action.
As an alternative, I have to go to any rich text editor field and there I could see attaching the Sitecore media files option, so attaching the media files in the RTE generates a link of media files with the .ashx extension then I have to copy that link of the attached media, then I use the link option available in the email template, as in the screenshot below to make it downloadable:
Is there any way in Sitecore to directly attach the media files in the email template?
| |
Sitecore does not support Async controller rendering. but from the Sitecore 8.2 it supports async MVC controllers.
If you want to use async actions, you need to use them outside of Sitecore contexts by indirectly invoking controllers via non-Sitecore routes or Html.RenderAction() on a Sitecore rendering. one other option is to use the AJAX base on your requirements.
But if you want to use that then follow - https://kamsar.net/index.php/2015/05/Enabling-Async-in-Sitecore-Controller-Renderings/
It’s a simple matter to patch Sitecore’s ControllerFactory, which is registered in the <initialize> pipeline:
<initialize>
<processor type="Foo.Pipelines.Initialize.InitializeAsyncControllerFactory, Foo.Core" patch:instead="*[@type='Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc']"/>
</initialize>
using Sitecore.Mvc.Controllers;
using Sitecore.Mvc.Pipelines.Loader;
using Sitecore.Pipelines;
using ControllerBuilder = System.Web.Mvc.ControllerBuilder;
The class to override the controller factory:
namespace Foo.Pipelines.Initialize
{
/// <summary>
/// Replaces the standard Sitecore MVC controller factory with one that knows how to do async action invocation.
/// </summary>
public class InitializeAsyncControllerFactory : InitializeControllerFactory
{
protected override void SetControllerFactory(PipelineArgs args)
{
SitecoreControllerFactory controllerFactory = new SitecoreAsyncControllerFactory(ControllerBuilder.Current.GetControllerFactory());
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
}
}
Then override the way the SitecoreControllerFactory patches the IActionInvoker on the controllers:
using System.Web.Mvc;
using System.Web.Mvc.Async;
using Sitecore.Mvc.Configuration;
using Sitecore.Mvc.Controllers;
namespace Foo
{
/// <summary>
/// Patches the normal Sitecore controller factory to enable executing async actions and using async/await
/// The ActionInvoker that Sitecore MVC wraps the inner action invoker with does not implement IAsyncActionInvoker,
/// which means ASP.NET MVC does not try to execute it async if needed, and precludes async/await.
/// </summary>
public class SitecoreAsyncControllerFactory : SitecoreControllerFactory
{
public SitecoreAsyncControllerFactory(IControllerFactory innerFactory) : base(innerFactory)
{
}
protected override void PrepareController(IController controller, string controllerName)
{
if (!MvcSettings.DetailedErrorOnMissingAction)
{
return;
}
Controller controller2 = controller as Controller;
if (controller2 == null)
{
return;
}
/* BEGIN PATCH FOR ASYNC INVOCATION (the rest of this method is stock) */
IAsyncActionInvoker asyncInvoker = controller2.ActionInvoker as IAsyncActionInvoker;
if (asyncInvoker != null)
{
controller2.ActionInvoker = new SitecoreAsyncActionInvoker(asyncInvoker, controllerName);
return;
}
/* END PATCH FOR ASYNC INVOCATION */
IActionInvoker actionInvoker = controller2.ActionInvoker;
if (actionInvoker == null)
{
return;
}
controller2.ActionInvoker = new SitecoreActionInvoker(actionInvoker, controllerName);
}
}
}
And finally, implement an override of SitecoreActionInvoker which implements IAsyncActionInvoker:
using System;
using System.Web.Mvc;
using System.Web.Mvc.Async;
using Sitecore.Mvc.Controllers;
namespace Foo
{
/// <summary>
/// Literally all this does is provider an IAsyncActionInvoker wrapper the same way SitecoreActionInvoker wraps non-IAsyncActionInvokers
/// This instructs ASP.NET MVC to perform async invocation for controller actions.
/// </summary>
public class SitecoreAsyncActionInvoker : SitecoreActionInvoker, IAsyncActionInvoker
{
private readonly IAsyncActionInvoker _innerInvoker;
public SitecoreAsyncActionInvoker(IAsyncActionInvoker innerInvoker, string controllerName) : base(innerInvoker, controllerName)
{
_innerInvoker = innerInvoker;
}
public IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state)
{
return _innerInvoker.BeginInvokeAction(controllerContext, actionName, callback, state);
}
public bool EndInvokeAction(IAsyncResult asyncResult)
{
return _innerInvoker.EndInvokeAction(asyncResult);
}
}
}
Then you can go forth and write lovely async controller renderings!
public async Task<ActionResult> AsyncActionMethod()
{
// download a bunch of URLs in parallel with await
var webClient = new WebClient();
var urls = new[] {
"https://google.com",
"https://bing.com",
"https://yahoo.com"
}.Select(url => webClient.DownloadStringTaskAsync(url));
var contents = await Task.WhenAll(urls);
// or just await one task
var google = await webClient.DownloadStringTaskAsync("https://google.com");
// execution will pick up right here when all the awaited tasks are done - thawing the thread to finish execution
return View(contents);
}
| Does Sitecore 10.2 support async code?
Say we have a SitecoreController which has async Task endpoints.. so my question is does sitecore support this async code? I have heard that there were some issues with async code while returning sitecore datasources and basically we only can have synch methods... is this true?
Thanks
| |
This error comes when you doesn't include the following scripts in your Layout file. Here are these scripts.
@Html.RenderFormStyles()
@Html.RenderFormScripts()
So the error is happening because you doesn't have those in your cshtml file. Try to add these and it will solve your issue.
Read the below article to know how to add.
https://mostlysitecore.wordpress.com/2018/08/29/a-better-guide-to-sitecore-9-forms/
| Sitecore Forms: Ajax is working on some pages but not on others for same form
I've got multiple pages that all use the same single form. I added the form to same additional pages of a different template. On the original pages, the form works as its supposed to - it shows the success message or validation errors in place on the page where the form was. However on the new pages, it redirects to /formbuilder?fxb.FormItemId=905cade2-cfe8-42f8-af72-2d7317835248&fxb.HtmlPrefix=fxb.1cbac25c-d3ff-494a-b282-cd9d369f2ece (whether it is success or validation error).
I know this is not an error with the submit actions since it does this for basic validation errors too (like if you leave the form blank and submit). This is the SAME form item in Sitecore, there is only one form item, and IsAjax is checked. What could be making it behave differently on different pages?
| |
It is a known issue and Sitecore provided a hotfix package for the same -
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1000608
Be aware that the hotfixes were built for specific Sitecore XP versions and must not be installed on other Sitecore XP versions or in combination with other hotfixes. In case any other hotfixes have already been installed on a certain Sitecore XP instance, send a request for a compatibility check to Sitecore Support.
| Incorrect datasource location being displaying in Experience Editor while adding new component
I am having an issue regarding datasource location while adding a component in experience editor.
The component datasource location is set to a particular datasource folder item(/sitecore/content/Site Data/Generic Content Items) in Sitecore.
The issue persists for every page item in Sitecore having some child items. When I'm adding this component in that page in Experience Editor, it displays current page as datasource location instead of Generic Content Item folder to select the datasource content item for the component.
While if I add the same component in any standalone page containing no child items, it displays correct datasource location(/sitecore/content/Site Data/Generic Content Items) to select the datasource content item in experience editor.
Is it a default behavior of the Sitecore? I'm using Sitecore version 9.2 and revision 002893
Is there a way to get rid of this problem and always display correct datasource location in Experience Editor as specified in component(rendering) item itself regardless of whether page having any child items or not?
Please find the below video link for the same reference:
https://www.screencast.com/t/kD6TQJLLYUUr
Below are my Sitecore instance details:
Sitecore version : 9.2.0
Revision Number : 002893
Please let me know if anything else is required.
| |
I was able to achieve this by applying rules on user group policy(Each user is assigned with some user groups with some permissions on it to access the asset).
I have used OOTB Content Hub taxonomy field "M.DRM.Restricted"(You can create your own new taxonomy)to add a rule on a user group which was assigned to the users that client was using and deselect the permissions which I don't want for the asset.
If "M.DRM.Restricted" field on an assets is "yes" then these restrictions will be applied else it won't. See screenshot for reference:
| Restrictions on an asset level in Content hub
Can we apply a restriction on an asset level to disable or remove the "create rendition button", "download user renditions" and "Public link option"?
I know we can do that on the user group level but the ask is to do it on particular assets.
| |
The issue was happening because of Firewall, we created a WAF rule allowing certain request URIs and the issue was resolved.
| Calling Script through a proxy from frontend to CDN
We are trying to implement "Partytown" to serve third-party scripts through webworker service where for metarouter the Script URL needs to come from CDN to which Sitecore has access but the frontend system is not having access. thus we are creating a proxy, frontend will give Sitecore a URL to access, and Sitecore should access that URL and return whatever it is there (the get request)
If I try to do a hit on the service from Sitecore I get the result while hitting it through the frontend system via the backend gives a 403.
I tried using [ServicesController] from Sitecore.Services.Core but did not resolve the issue. Trying it through CORS but any leads on this are welcome.
ERROR SAYS : Strict origin when ross origin
| |
I suspect this is because of the base template that you are using for your parameters.
Please can you verify that the parameters template that you are assigning inherits the Standard Rendering Parameters. If not, try switching to that base template and see if it fixes the issue.
You can find the Standard Rendering Parameters template here:
/sitecore/templates/System/Layout/Rendering Parameters/Standard
Rendering Parameters
| Vanishing Data Source, Placeholder, etc Fields When Rendering Parameters Template Set
In Sitecore 10.1, when I set the Parameters Template in my rendering, the Edit component properties dialog shows the expected parameters fields but all other fields, including Data Source, Placeholder, Caching etc do not show...
As soon as I set the Parameters Template value to None, they return.
What is causing this? What needs to be done so that all fields show?
| |
Child items will not editable you need to use Edit Frame:
Edit Frame
With an edit frame you can surround a section of html within your view with a clickable target, that will display a toolbar with a button to launch the dialogue.
To set up an edit frame:
In the core database navigate to /sitecore/content/Applications/WebEdit/Edit Frame Buttons and create a new item based on Edit Frame Button Folder. This folder will be referenced in your view for the collection of buttons to be displayed.
Under the new folder create a new item based on Field Editor Button and give it the name of your button.
On your button item make sure you set an icon and the list of fields the button should allow the content editor to edit. These should be pipe separated.
In Visual Studio open the view for your rendering
Add a reference to Sitecore.Mvc.Extensions
Surround the section to show the button with a using block as follows:
@using (Html.BeginEditFrame(RenderingContext.Current.ContextItem.Paths.FullPath, "Button Folder Name", "Toolbar Title"))
{
// HTML here
}
You can use @testimonial.Description and child content will be editable through Edit Frame
More detail available here https://himynameistim.com/blog/custom-experience-buttons-vs-edit-frames-in-sitecore
| Sitecore Experience Editor does not work for the fields rendering inside foreach loop
Trying to make a component experience editable. However, having some issues with Fields those are getting rendered through loop.
Any suggestion is really appreciated.
| |
It can be a bit tricky to help with these issues without being familiar with the individual set up (more screenshots / URLs are always appreciated). The following additional information would help:
Where you are creating this rule
Screenshots of the pipeline batches / pipeline steps
Screenshots / examples of the relevant info in xDB (particularly the data formats)
For clarity, it sounds like you're creating a segmented list in the List Manager based on a rule and you don't see all of the lists that you're expecting.
Note that I only have access to a 9.3 instance at the moment.
Please verify / note / perform the following:
You do not see any errors in the logs of the connector, Solr, Sitecore, or XConnect
The correct tenant is selected in the rule (I notice that yours says "Branch" -- is it possible that you selected the branch template instead of the instantiated item?)
Make note of any differences between the lists that you do see vs. the ones that you don't
That the ID specified in your rule matches the format in the database or in any DEF config item(s)
Nothing is "stuck" in your staging database
Try to replicate the issue on a fresh install of XP + Connector
Check if Solr has the data you're expecting
You have members stored in xDB and their facets are populated
You can see the contacts in Experience Profile
Create a new tenant and start over
Decompile and step through the relevant code
Troubleshoot by using the List Manager API https://doc.sitecore.com/xp/en/developers/92/sitecore-experience-manager/the-list-manager-api.html
Only contact lists can be used as a list source. If you want to use a segmented list as a list source, you must first convert the segmented list to a contact list (this is mentioned in the Sitecore docs).
If a contact list is created but not activated, you can activate it as part of the workflow by changing the Draft state to Deployed (this is mentioned in the Sitecore docs).
Contact list definitions appear in the index only when they are activated using the Marketing Operations API or they are saved with the activated flag set to True (this is mentioned in the Sitecore docs).
Do the following:
Deploy marketing definitions
Populate Solr Managed Schema
Reindex
Restart IIS
| Dynamic CRM Connector not showing all Marketing List
I am using Sitecore 10.2 with Dynamic CRM Connector, I run two pipelines
Dynamics Marketing Lists to xDB Reference Sync
Dynamics Marketing Lists to xConnect Sync
Both pipelines are working fine with no errors, but when I go to list the manager and create a segmented list then add the rule where contact is a member of specific list from the Dynamics tenant specific, I can not see all lists which is available in CRM.
| |
Instead of recycle bin you can choose to archive the item, as it won't delete the data but manage in a different way, sitecore have OOTB capability for it and you can get different modules and other options in marketplace for same(e.g. Version Pruner).
Some links for your reference:
https://sitecoreconfig.wordpress.com/2015/09/21/archiving-sitecore-content-and-the-recycle-bin/#:~:text=The%20Sitecore%20archive%20is%20similar,this%20archiving%20framework%20is%20extensible.
https://doc.sitecore.com/xp/en/users/92/sitecore-experience-platform/archive-and-restore-an-item.html
We also do it in our project using PS script (which internaly uses ArchiveVersion cmdlet).
Let me know if it helps or do you need any other information.
| Keeping old item versions
We have some items with 100+ versions. We have decided to recycle the old item versions and keep the last 10 versions. By default, anything in the recycle bin will be permanently deleted in 30 days.
The issue is we will lose the old version items in 30 days in the recycle bin. We don't want to delete the versions permanently. Due to some legal requirements, we will need to refer back to any item version whenever we want.
Is there any third-party integration that has anyone used which can keep every item version so we can refer to any past version at any time? Or anyone has come up with a solution for keeping the items up to 10 versions and storing the old versions somewhere and not deleting them permanently?
Any suggestions would be appreciated
| |
To get all SearchEvents you will need to make a call to XConnect.
Something like this should do the trick:
using (XConnectClient xConnectClient = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
var searchs = new List<SearchEvent>();
Guid SearchDefinitionID = new Guid("0c179613-2073-41ab-992e-027d03d523bf");
var interactions = await xConnectClient.Interactions.Where(interaction => interaction.Events.Any(ev => ev.DefinitionId == SearchDefinitionID)).ToList();
foreach (var interaction in interactions)
{
foreach (SearchEvent ev in interaction.Events.Where(ev => ev.DefinitionId == SearchDefinitionID).ToList())
{
searchs.Add(ev);
}
}
}
If you are going to be doing regular data extraction and processing from XConnect. I believe it is recommended to use the Sitecore Cortex engine and its projection framework:
https://doc.sitecore.com/xp/en/developers/102/sitecore-experience-platform/projection-framework.html
You could use this to project, group and count data as required. This uses distributed workers, so can be alot faster and more efficient.
I found this to be a great resource if you are interested in the above:
https://github.com/adeneys/cortex-processing-demo
| Get Most Popular Search Terms from PageEvent xDB
I have manually trigger a search event based on Sitecore in standart way:
var searchEvent = Tracker.MarketingDefinitions.PageEvents[AnalyticsIds.SearchEvent.Guid];
Sitecore.Analytics.Tracker.Current.CurrentPage.Register(new PageEventData(searchEvent.Alias, searchEvent.Id)
{
Data = "sitecore experience platform"
});
but after I need to find the most popular or latest search,
not for one specific ContactReference, but globally by site.
how I could do it programmatically ?
| |
The ProxyConfig.proxyOptions.secure setting likely isn't applicable in this case because there is no proxy involved. Also, as the docs state, disabling SSL isn't a great practice.
Instead of trying to disable SSL validation to fix my issues, I opted to make SSL validation work by adding my SIF Trusted Root certificate to Node. In short:
setx NODE_EXTRA_CA_CERTS C:\some\path\to\my-shiny-sif-certificate.cer
Sitecore has a solid guide:
https://doc.sitecore.com/xp/en/developers/hd/200/sitecore-headless-development/walkthrough--configuring-sitecore-ca-certificates-for-node-js.html
I also wrote a bit more about this subject:
https://sitecore.marcelgruber.ca/posts/nextjs-unable-verify-first-certificate
| JSS/NextJS: how to disable SSL cert validation via ProxyConfig.proxyOptions.secure setting
I'm running in connected mode on my local and I want to disable SSL cert validation. According to the Sitecore docs, this option is mentioned:
... in the SSR application jss-proxy-ssr, in the config.js file, in the proxyOptions object, you can disable SSL validation entirely by setting the secure to false option. For example:
proxyOptions: {
// Setting this to false will disable SSL certificate validation
// when proxying to a SSL Sitecore instance.
// This is a major security issue, so NEVER EVER set this to false
// outside local development. Use a real CA-issued certificate.
// NEVER EVER do this in production. It will make your SSL completely insecure.
secure: false
}
It's not clear how to actually do this. I started by searching for proxyOptions in the JSS repo. I looked into making the change in bootstrap.ts via the configOverride var, but it's only a simple list of key value pairs which doesn't appear to support tunnelling into ProxyConfig.proxyOptions.secure:
const configOverride: { [key: string]: string } = {};
| |
You will find the logic of this confirmation box under Sitecore.Kernel DLL. If you extract the DLL, you will find the logic of the confirmation box that is written under the class Sitecore.Shell.Framework.Commands.PublishItem. Under the below method, this is written.
private static bool CheckWorkflow(ClientPipelineArgs args, Item item)
{
Assert.ArgumentNotNull((object) args, nameof (args));
Assert.ArgumentNotNull((object) item, nameof (item));
if (args.Parameters["workflow"] == "1")
return true;
args.Parameters["workflow"] = "1";
if (args.IsPostBack)
{
if (args.Result == "yes")
{
args.IsPostBack = false;
return true;
}
args.AbortPipeline();
return false;
}
SiteContext site = Factory.GetSite("publisher");
if (site != null && !site.EnableWorkflow)
return true;
IWorkflowProvider workflowProvider = Context.ContentDatabase.WorkflowProvider;
if (workflowProvider == null || workflowProvider.GetWorkflows().Length == 0)
return true;
IWorkflow workflow = workflowProvider.GetWorkflow(item);
if (workflow == null)
return true;
WorkflowState state = workflow.GetState(item);
if (state == null || state.FinalState)
return true;
args.Parameters["workflow"] = "0";
if (state.PreviewPublishingTargets.Any<string>())
return true;
SheerResponse.Confirm(Translate.Text("The current item \"{0}\" is in the workflow state \"{1}\"\nand will not be published.\n\nAre you sure you want to publish?", (object) item.DisplayName, (object) state.DisplayName));
args.WaitForPostBack();
return false;
}
Now What you can do is create your own processor and use yours in the case of the OOTB given below. For this, you need to create a patch.
<command name="item:publish" type="Sitecore.Shell.Framework.Commands.PublishItem,Sitecore.Kernel"/>
For the whole implementation, you can refer to this blog.
https://blogs.perficient.com/2018/09/21/looking-for-ways-to-customize-warning-messages-in-sitecore-content-editor/
Finally when it uses SheerResponse.Confirm then it will show the confirmation box like it is showing. So if you don't want to show the buttons then you can use SheerResponse.Alert.
| edit sitecore confirm box popping up when publish an item in draft state
When we try to publish any Sitecore item in the draft workflow state then after clicking on publish we get a confirmation box as shown in the image.
I need to customize this popup (Edit its text and remove "OKAY" button). Please let me know where to find its code.
| |
I beleive that before starting the rebuild you have successfully configured the secondary Reporting database and updated the connection strings accordingly as this is a must-to-have step, see more here.
The process of rebuilding the reporting database can take a very long time, this is a known fact on the big volumes of data. You can monitor its status on the RebuildReportingDB.aspx page by looking at the details in the Processed column, which shows how many entries have been processed. The EstimatedTotal column displays the total number of entries to be processed.
To improve the overall performance of the rebuild I suggest to revisit your configuration of the processing agents as you may need to increase the number of the aggregation agents/threads you run:
Open the Sitecore.Analytics.Processing.Aggregation.Services.config
file;
Edit the maxAgents setting for the History Worker to specify the maximum number of threads that you want to run on the server.
Note, that the History Worker is the key agent involved in the historical data rebuild. To speed up the rebuild process you have to increase its maximum number of threads and then set it back to 1 again when the rebuild finishes. Read more here about processing agents.
| Speed up Rebuilding Reporting Database
Analytics data since September 1 is missing for a Sitecore customer. We are trying to rebuild the reporting database in Production (Sitecore 10.2). There are approximately 60+ Lacs of data. The process is going really slow (It shows 255 done after running it for more than 2 days).
There is a 'Minimum StartDateTime' field in the RebuildReportingDB.aspx which I have tried to use and provided a value of September 1. I'm trying to run this in a lower environment and even though this is going a little faster, I suspect that the data before September 1 will be lost.
So I would like to know if there are any alternatives or something can be done to expedite the process?
| |
Unfortunately this feature is not available on the new learning portal yet. All links to my previous certifications stopped working and I am not able to get a public link to the new certifications too.
So I keep adding my certifications manually to LinkedIn for the time being:
Go to the section Licenses and Certifications on the LinkedIn profile page
Click the plus icon and fill in the form:
Name and Issue date - this information can be copied from the certificate
Issuing organization - start typing and select Sitecore from the dropdown
Credential URL - you can keep this field empty and edit it in future if the Learning portal introduces public certification links again
If you are not sure how to find your certificate on the learning portal, go to the Learning Home and click 'My Transcript' link at the bottom right corner of the page. Then switch to the 'Courses' tab and scan through the list until you find the correct exam. The last column should show a clickable certification icon that allows to download a copy of certificate:
| how to add my certifications to linkedin
Since the learning portal has changed, I cannot see an option to add my certifications to LinkedIn anymore. Previously, the portal used to display the certifications with a link to add them to LinkedIn.
Could you please provide me with suggestions and/or point me in the right direction?
Thank you!
| |
The issue is with Metro and TimeZoneInfo types.
Either remove them or make sure that they are registered properly in your model and have proper constructors.
Read more about type restrictions here:
https://doc.sitecore.com/xp/en/developers/91/sitecore-experience-platform/the-xconnect-model.html
| Unable to get contacts,SitecoreXConnectClientConfiguration.GetClient() throwing an exception
I'm trying to get the contacts but while creating an instance of xconnect client, I'm getting the following exception:
Type must have a parameterless constructor (not necessarily public) or a public constructor that only takes parameters that correspond to primitive types
Here is the pseudo code for reference.
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
List<Contact> contacts = null;
contact = client.Get<Contact>(new IdentifiedContactReference(AssemblyFacetInformation.ContactReference, "bcc746fa19cd6fddf0203aa443eebd11"), new ContactExecutionOptions(new ContactExpandOptions(AssemblyFacetInformation.ContactReference)));
var contact = contacts.FirstOrDefault();
var assemblyFacetInformation = contact.GetFacet<AssemblyFacetInformation>(AssemblyFacetInformation.Timezone);
assemblyFacetInformation.TimeZone = windowsTimeZone;
client.SetFacet(contact, AssemblyFacetInformation.Timezone, assemblyFacetInformation);
client.Submit();
}
My Custom model class
public class AssemblyFacetCollectionModel
{
public static XdbModel Model { get; } = BuildAssemblyModel();
static XdbModel BuildAssemblyModel()
{
XdbModelBuilder xdbModelBuilder = new XdbModelBuilder("AssemblyFacetInformation", new XdbModelVersion(1, 0));
xdbModelBuilder.ReferenceModel(CollectionModel.Model);
xdbModelBuilder.DefineFacet<Contact, AssemblyFacetInformation>(AssemblyFacetInformation.DefaultFacetKey);
return xdbModelBuilder.BuildModel();
}
}
This is my facet class
[FacetKey(DefaultFacetKey)]
[Serializable]
public class AssemblyFacetInformation : Facet
{
public const string IdentifierCookieName = "_assembly_visitor_id";
public const string AnalyticsCookieName = "analytics_uuid";
public const string MetroCookieName = "metro";
public const string ContactReference = "Assembly_Visitor";
public const string DefaultFacetKey = "AssemblyFacetKey";
public const string Timezone = "Timezone";
public AssemblyFacetInformation() { }
[JsonProperty("metro")]
public Metro metro { get; set; }
[JsonProperty("geolocated_location")] //From "metro" Cookie
public string GeoLocation { get; set; } //From "metro" Cookie
[JsonProperty("distance_from_metro")]
public float DistanceFromMetro { get; set; } //From "metro" Cookie
[JsonProperty("latitude")]
public float UserLatitude { get; set; } //From "metro" Cookie
[JsonProperty("longitude")]
public float UserLongitude { get; set; } //From "metro" Cookie
[JsonProperty("prioritize_online")]
public bool PrioritizeOnline { get; set; } //From "metro" Cookie
//[JsonProperty("metro")]
//public string ShopSession { get; set; } //From "_shop_session" Cookie
[JsonProperty("time_zone")]
public TimeZoneInfo TimeZone { get; set; }
}
While debugging the process I found that exception originally thrown by the AssemblyFacetCollectionModel class on this line
return xdbModelBuilder.BuildModel();
Did I miss something or doing anything wrong??
| |
One way to do this is to use the section in your web.config.
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/applicationinitialization/
This will load the pages you define when the app starts, so if you choose those pages wisely you can fill some caches.
Example:
<system.webServer>
<applicationInitialization remapManagedRequestsTo="initializing.html" doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/" hostName="www.xxx.com"/>
<add initializationPage="/en/products" hostName="www.xxx.com"/>
</applicationInitialization>
| Azure Site "Warm Up" After Deployment
The Azure sites take a long time to re-cache and "warm up" after the deployment is complete. I want something to use Azure Devops to programmatically hit the CMS (content editor and experience editor) as well as the CD server to begin the re-caching process and make the environments usable again as quickly as possible.
| |
At the risk of taking this post into subjective space (although your post leans in this direction already), in my view you're actually working a problem in your general approach and trying to solve it with technology.
Use the APIs, don't re-create them
First of all; you're not giving the Sitecore APIs a fighting chance of implementing any layer of caching, since you're essentially bypassing it entirely by taking it straight down to the basics of .GetItem() based off a field value.
Multilist field actually has methods to draw out either the TargetIDs and a .GetItems() method - both of which you should be using as opposed to string splitting and individual .GetItem calls. Why? Because this is where Sitecore would have a chance to utilize some level of caching. Not that it does, to my knowledge, but that's not really the point. You shouldn't bypass native API functionality and cook your own.
If you're going to build your own methods, make your abstraction on a higher level and implement the caching that would help yourself, as in get the TargetIDs from your field, return items from your own cache and only do .GetItem on the ones you don't have in the cache. Your cache here can (almost) be completely static - menu navigation lists don't change all that often in real life. Drop the cache on a publish event.
Why the search index didn't help you
It didn't help because you're esentially doing the same thing. But instead of going to Sitecore to get the list of TargetIDs you instead take a roundtrip to Solr to do the same thing. And THEN you still go back to doing individual .GetItem() calls to get to your items. You're not saving anything - using Solr to do a string split for you isn't helping anyone.
For the index approach to give you any kind of improvement, you need to think about it way differently. What you need to arrive at, is a situation where you can query solr for "all of the items that this multilist field has selected" and return the Navigation Title for each of them. And then return a string array as opposed to Sitecore Items. You don't NEED a full Item to build your navigation - presumably - you only need the text that goes into the menu.
The index approach can absolutely be made to be your most effecient approach to all of this - but it requires you to actually use the index for its strengths. Use it to return your end result, don't use it to return an intermediate result that you then anyway end up sending into Sitecore low level API calls.
| What is the best practice approach to populating a navigation component
I have been spending a bit of time looking at the Sitecore Debugger. Using this you can see the 'hotspots', the components on the page that take the longest time to load and make the most calls to the database.
One of these hotspots in our implementation is the primary navigation component, which as you can imagine has to read lots of items in order to determine what to include in the menu. This got me thinking, about how we might improve our implementation and also to wondering what the best practice approach was.
As a brief intro to our approach, we do the following:
Settings node has MultiList field for "PrimaryNavigation" Items (these form top level)
Each PrimaryNavigation Item also has a MultiList field for "Sections" (these form sections within a dropdown)
Each section has a MultiList field for "MenuItems" (which is effectively the final link)
Much of the data retrieval utilizes a method called GetLinkedItem, which cycles through the various MultiList fields grabbing the items for the menu.
public static List<Item> GetLinkedItems(Database database, string fieldValue)
{
var items = new List<Item>();
if (!string.IsNullOrEmpty(fieldValue))
{
var ids = fieldValue.Split(new char[] { '|' });
foreach (var id in ids)
{
var linkedItem = database.GetItem(new Sitecore.Data.ID(ParseId(id)));
if (linkedItem != null && !linkedItem.Publishing.NeverPublish)
{
items.Add(linkedItem);
}
}
}
return items;
}
With this approach, the debugger is showing some 4500 item reads to populate a menu that contains approximately 150 items.
I think one of the reasons for the discrepancy is that when an item is loaded, it also reads its child items. Either way, this seems to me to be a bit inefficient.
My first thought was to try getting the data from the web index, with code similar to the one below:
public static List<ContentSearchModelBase> GetLinkedItemsFromIndex(Database database, string fieldValue)
{
var items = new List<ContentSearchModelBase>();
if (!string.IsNullOrEmpty(fieldValue))
{
var ids = fieldValue.Split(new char[] { '|' }).Select(x => new ID(x));
var index = database.Name == "master" ? "sitecore_master_index" : "sitecore_web_index";
using (var context = ContentSearchManager.GetIndex(index).CreateSearchContext())
{
var q = context.GetQueryable<ContentSearchModelBase>()
.Where(x => !x.NeverPublish && ids.Contains(x.ItemId)).GetResults();
var result = q.Hits.Select(h => h.Document).ToList();
if (result != null)
return result;
}
}
return items;
}
However, whilst this reduced the number of Item reads, it was drastically less efficient!
I appreciate in the grand scheme of things - when the component gets cached the overhead becomes less of an issue. But I was wondering if anyone can recommend a better more efficient approach to building a multi-layer navigation menu component?
| |
I assume you are trying it with GraphQL GUI and my understanding is that the question is how to pass a query variable dynamically to the query or mutation.
Here I'm trying to update the Title field value of Home item with following code.
mutation UpdateItem($datasource: String!,$language: String!, $fields: [FieldValueInput!]) {
updateItem(
path: $datasource,
language: $language,
fields: $fields){
... on SampleItem {
title {
value
}
}
}
}
Query variable:
{
"datasource":"/sitecore/content/home",
"language":"en",
"fields": [{
"name": "title",
"value": "'Example Item with changed title'"
}]
}
It will look like this in GraphQL Playgrond.
Also you can check the schema by clicking Docs button at the right side. The API documentation tab is one of the most exciting features of GraphQl Playground. It enables you to preview GraphQL queries, GraphQL type details, and a single field of a given schema.
Hope this helps!
| How to pass query variables in graphql
I couldn't find a way to pass query variables to my graphql query, I've made a query which I think is how I'd be able to do mutation
mutation UpdateItem($datasource: String!, $language: String!, $fields: String!) {
updateItem(
path: $datasource
language: $language
fields: $fields
){
... on SampleItem {
title {
value
}
}
}
}
but I couldn't figure out how to pass my query variables.
I found this in the stackexchange How to pass a variable to search context? but I couldn't find the GraphQLData library
Any enlightenment on this matter would be greatly appreciated, Thanks in advance!
| |
Yes, that's correct - actually Experience Edge is not tagged as a separate feature with Content Hub One. We offer globally distributed GraphQL APIs powered by Experience Edge. It is just a part of the Content Hub One offer and price.
(This was from the Sitecore Product team)
| Sitecore Content Hub One with inbuild Experience Edge support?
Sitecore has just launched its new product "Content Hub One" for headless development. Has it inbuild Experience Edge support?
I know we can also create headless applications with existing content hub CMP module with experience edge but that comes with separate license.
| |
I have had a go at implementing a validation rule that checks the field is less than 10 characters. Please try this out:
Duplicate an existing validation rule, that already uses sitecore RegexValidator.
These can be found here:
/sitecore/system/Settings/Validation Rules/Field Rules/Common/
Name the item "Less than 10 Chracters" and give Title/Description.
Update Paramaters field to:
Pattern=^.{0,10}$&Text=Field "{0}" must be less than 10 Characters.
Add the validation rule
Go to you field that you would like to validate and add the new validation action:
Test that it works
Go to your item and add more than 10 characters into your field.
Press the validate button.
| Regex based string length validation in Sitecore Rich Text Editor not working
I applied one regex in the validation field to check if the entered characters in the RTE are less than 520 characters only, otherwise, it shows the error.
I've setup the validation as follows:
But this regex is not matching exactly, even when I enter the 518 characters it throws the error (setup in the validation text field).
I thought that may be the regex is not correct but when I used the online regex tester tool then it is behaving correctly.
So, before raising it to the Sitecore team I thought to confirm here.
I also tried to use the existing validation rules in the /sitecore/system/Settings/Validation Rules/Field Rules/Sample/Max Length 40 and I tried this also but it was not working and I was unable to change the message that the client wants to see when string length doesn't match the criteria.
So, I am just confirming if someone has any solution to why regex not working or raise it with the Sitecore support team.
FYI: My environment is Sitecore 10.2 MCC with SXA
| |
No, that's not possible out of the box.
Sitecore Image Field allows to select image from Media library item only.
| Can we specify External image source in Sitecore Image Field
Is it possible to specify an external image source for a Sitecore Image Field?
So that an author can also visualize it in the content editor and not need to store in Sitecore media.
| |
By default ordering of tabs is set to alphabetical order of folders which contain components (their Display Names).
With SXA you can use the checkbox on Presentation/Available Renderings item called Group renderings in sections according to Available Renderings items in the site.
| Is there any way I can order Rendering tabs?
Is there any way I can order Rendering tabs to appear when adding a new component to the page? I tried this from available rendering but it didn't work out
| |
I had the same problem. You can see a version of MSBuild in a configuration of your custom gulp script, and the version that you have on your pc. My one was installed with Visual Studio and was 17, the version of VS was 22, so I decided to install VS 19 and problem was gone.
| gulp publish problem: 'spawn C:\windows\microsoft.net\Framework64\v(not used)\msbuild.exe ENOENT'
I try to publish my Sitecore project solution using a custom-made script. I run the gulp publishSitecoreSolution command (a custom-made one), and I get this output in PowerShell:
[15:55:04] Loading C:\users\USERNAME\source\repos\PROJECT_FOLDER\sitecore-training-project\gulpfile.js\tasks\publishProject.js
[15:55:04] Using gulpfile C:\users\USERNAME\source\repos\PROJECT_FOLDER\sitecore-training-project\gulpfile.js
[15:55:04] Starting 'publishSitecoreSolution'...
publish starting
publish starting
publish starting
publish starting
publish starting
publish starting
publish starting
publish starting
[15:55:08] 'publishSitecoreSolution' errored after 3.88 s
[15:55:08] Error: spawn C:\windows\microsoft.net\Framework64\v(not used)\msbuild.exe ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
There are but a few threads on the internet dealing with this, like the one here Issue while Setup Habitat 1.8.1 on Sitecore 9.2 "Error: spawn C:\Windows\microsoft.net\Framework64\v(not used)\msbuild.exe ENOENT". It's similar, but not the same.
So far I tried looking through the registry, after that looking at folder contents in the path outlined in error text (screenshot below),
then I tried logging whatever I could in the gulpfile, such as the contents of the msbuild object, and here's what console.table(msbuild) gives
I'm including the code snippet where the msbuild object I'm logging is defined and where the function publishSitecoreSolution that is executed by gulp is defined:
var gulp = require("gulp");
var _msbuild = require("msbuild");
var argv = require("yargs").argv;
var glob = require("glob");
function publishProject(src, publishProfile){
var msbuild = new _msbuild();
msbuild.sourcePath = src;
msbuild.version = $.config.msBuildVersion;
msbuild.overrideParams.push("/p:PublishProfile=" + publishProfile);
msbuild.publish();
};
async function publishSitecoreProject(){
var src = argv.layer + "/" + argv.name + "/code/*.csproj";
var publishProfile = (argv.publishProfile === undefined) ? "Default" : argv.publishProfile;
var filePath = glob.sync(src)[0];
if(filePath != "undefined"){
publishProject(filePath, publishProfile);
} else{
console.log("Project does not exist!");
}
};
async function publishSitecoreLayer(){
var src = argv.layer + "/**/code/*.csproj";
var publishProfile = (argv.publishProfile === undefined) ? "Default" : argv.publishProfile;
var filePathes = glob.sync(src);
if(filePathes.length > 0){
filePathes.forEach(async function(filePath){
publishProject(filePath, publishProfile);
});
} else{
console.log("Layer does not exist or empty!");
}
};
async function publishSitecoreSolution(){
var src = "./**/**/code/*.csproj";
var publishProfile = (argv.publishProfile === undefined) ? "Default" : argv.publishProfile;
var filePathes = glob.sync(src);
if(filePathes.length > 0){
filePathes.forEach(async function(filePath){
publishProject(filePath, publishProfile);
});
} else{
console.log("Layer does not exist or empty!");
}
};
gulp.task("publishSitecoreProject", publishSitecoreProject);
gulp.task("publishSitecoreSolution", publishSitecoreSolution);
gulp.task("publishSitecoreLayer", publishSitecoreLayer);
I've the latest .NET SDK installed.
I simply don't know where to look or what to do anymore. Any help is appreciated! Thanks-
| |
Unfortunately, the Sitecore.Framework.Runtime.Build SDK as outlined in the documentation only works for .Net Standard 2.1, which is not compatible with Visual Studio 2022 Build Tools.
The project must be built against Visual Studio 2019 Build Tools.
To build the project in Azure Pipelines, use the windows-2019 agent.
To build the project inside a docker container, use mcr.microsoft.com/dotnet/framework/sdk:4.8-20211012 which contains Visual Studio 2019 Build tools.
| Building External Identity Provider subproviders integration in Identity Server for 10.0 - 10.2 in Visual Studio 2022 for Author Access
I am getting errors when compiling my subprovider implementation (Okta) with Identity Server in Visual Studio 2022.
I have followed all the instructions as described in https://doc.sitecore.com/xp/en/developers/102/sitecore-experience-manager/use-the-sitecore-identity-server-as-a-federation-gateway.html
This is all working fine when compiling in Visual Studio 2019.
| |
I think one step you have missed to deploy "Deploy custom Facet model to XDB".
To Deploy the custom facet model to XDB you need to serialize the collection model in which you defined your custom facet model. To serialize into JSON prefer Console application to generate the JSON file.
class Program
{
static void Main(string[] args)
{
var serlizableModel = XdbModelWriter.Serialize(CustomFacetCollectionModel.Model);
File.WriteAllText(CustomFacetCollectionModel.Model.FullName + ".json", serlizableModel);
}
}
On execution of the console application, it will generate a JSON file. Copy that JSON file and paste to the below places for single instance:
x-connect root path > App_data/Models
x-connect root path > App_data/jobs/continuous/IndexWorker/App_data/Models
For scaled environment deploy json in below location:
All instances of xConnect Collection
All instances of xConnect Collection Search
xConnect Search Indexer
Marketing Automation Operations
Marketing Automation Engine
Content Delivery
Content Management
xDB Processing
| One or more local models conflict with the xDB service layer. 'AssemblyFacetKeyModel, 1.0' does not have a remote version'
I have added a new model for my custom facets but it's throwing the following exception while calling the GetClient() method.
One or more local models conflict with the xDB service layer. 'AssemblyFacetKeyModel, 1.0' does not have a remote version'
Model builder class
public class AssemblyFacetCollectionModel
{
public static XdbModel Model { get; } = BuildAssemblyModel();
private static XdbModel BuildAssemblyModel()
{
XdbModelBuilder xdbModelBuilder = new XdbModelBuilder("AssemblyFacetKeyModel", new XdbModelVersion(1, 0));
xdbModelBuilder.ReferenceModel(CollectionModel.Model);
xdbModelBuilder.DefineFacet<Contact, AssemblyFacetInformation>(AssemblyFacetInformation.DefaultFacetKey); //value >> AssemblyFacetKey
return xdbModelBuilder.BuildModel();
}
}
Custom Facet model class
[FacetKey(DefaultFacetKey)]
[Serializable]
public class AssemblyFacetInformation : Facet
{
public const string IdentifierCookieName = "_assembly_visitor_id";
public const string AnalyticsCookieName = "analytics_uuid";
public const string MetroCookieName = "metro";
public const string ContactReference = "Assembly_Visitor";
public const string DefaultFacetKey = "AssemblyFacetKey";
public const string Timezone = "Timezone";
public AssemblyFacetInformation() { }
//[JsonProperty("metro")]
//public Metro metro { get; set; }
[JsonProperty("geolocated_location")] //From "metro" Cookie
public string GeoLocation { get; set; } //From "metro" Cookie
[JsonProperty("distance_from_metro")]
public float DistanceFromMetro { get; set; } //From "metro" Cookie
[JsonProperty("latitude")]
public float UserLatitude { get; set; } //From "metro" Cookie
[JsonProperty("longitude")]
public float UserLongitude { get; set; } //From "metro" Cookie
[JsonProperty("prioritize_online")]
public bool PrioritizeOnline { get; set; } //From "metro" Cookie
//[JsonProperty("metro")]
//public string ShopSession { get; set; } //From "_shop_session" Cookie
//[JsonProperty("time_zone")]
//public TimeZoneInfo TimeZone { get; set; }
}
This is where I'm setting the value
protected virtual void MapTimeZoneFacet(JObject jsonObject)
{
Assert.ArgumentNotNull(jsonObject, "jsonObject");
var olsonTimeZone = jsonObject["timeZone"].Value<string>();
var windowsTimeZone = Helpers.Extensions.UserTimeZoneInfo.OlsonTimeZoneToTimeZoneInfo(olsonTimeZone);
using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
{
Contact contact = null;
try
{
contact = client.Get<Contact>(new IdentifiedContactReference(AssemblyFacetInformation.ContactReference, "**value**"), new ContactExecutionOptions(new ContactExpandOptions(AssemblyFacetInformation.ContactReference)));
var assemblyFacetInformation = contact.GetFacet<AssemblyFacetInformation>(AssemblyFacetInformation.DefaultFacetKey);
// assemblyFacetInformation.TimeZone = windowsTimeZone;
client.SetFacet(contact, AssemblyFacetInformation.Timezone, assemblyFacetInformation);
client.Submit();
}
catch (Exception ex)
{
var test = jsonObject;
}
}
}
Did I miss something or doing anything wrong?
| |
You can allow Mvc Form rendering in placeholder which is available in this location /sitecore/layout/Renderings/System/Forms/Mvc Form and then select form data source.
| Sitecore Form from Experience Editor
Can someone please tell me if It is possible to add Sitecore forms from in Experience Editor ?
| |
As per Sitecore documents - https://doc.sitecore.com/cdp/en/developers/sitecore-customer-data-platform--data-model-2-1/send-additional-event-data-to-sitecore-cdp.html
below is a list of guidelines for using the events data extension:
Only one data extension per event type is supported.
The name of the event data extension must be ext.
The key of the event data extensions must be default.
The attribute name must be alphanumeric [A-Z,a-z,0-9] as per the json rfc7159 spec.
The attribute name of the event data extension must be written in camelCase.
The attribute name must be unique within the entire event type.
The attribute name of the event data extension must be meaningful. Consider using the friendlyID.
If grouping is required, use common prefixes.
An event data extension has a maximum of 50 attributes.
| Maximum number of additional attributes can be added using 'ext' in Sitecore CDP?
I'm exploring Sitecore CDP capabilities and want to know about the maximum number of recommended values for additional attributes that can be added using 'ext' as key-value pair in Sitecore CDP.
| |
I think this issue is because of the Node js version over the period of time few dependent packages are deprecated. Therefore it does not support the latest node/npm version.
I tried the below steps and it got resolved:
Install node js version 13.14.0
Add jss CLI globally using : npm install -g @sitecore-jss/[email protected]
jss create my-jss-app angular --branch release/13.0.0
| jss create command is not available in sitecore jss cli version 13
I'm trying to create new jss app for Sitecore 9.3. I have installed sitecore jss-cli version 13.0. When I try to create new jss app using "jss create" command nothing is happening. where in I'm able create an app using the command "npm init sitecore-jss". It looks like create command itself is not available.
Node version installed: v18.12.1
JSS CLI version: 13.0.0
npm version: 9.1.2
| |
Sitecore can collect telemetry metrics associated with certain Sitecore environments to help understand how their platform is used.
One of the metrics is called XM.Foundation.Core.Nexus.WebSessions and it counts the number of web sessions on the website. To avoid tracking the same session multiple times, Sitecore saves a flag sc_ct_trk=1 to the current session data after the session has been counted by the telemetry client. Therefore, in all subsequent requests Sitecore will know that this session has already been added to the metric and there is no need to count it again.
As far as I can see, this flag is saved to the session storage rather than cookies so this flag is only accessible from your server infrastructure and not visible to the end users. The only possible value is 1 and no personal data is associated with this metric.
This functionality is implemented in one of the core Sitecore HTTP modules hence I would not recommend disabling it without contacting Sitecore. This knowledge base article says that Sitecore can provide a no-track license file and you can contact your Sitecore account representative for more information.
| Sitecore 10.2 creates session data "sc_ct_trk"
We recently migrated from Sitecore 9 to 10.2 and now we see a strange cookie in the session data named sc_ct_trk. I looked all up the internet and found no reference to what this is or how to disable it.
Any ideas?
| |
To enable the graphQL endpoint to try the below steps
Download and install packages.
For use of Sitecore JSS with versions of Sitecore prior to 10.1
https://dev.sitecore.net/Downloads/Sitecore_JavaScript_Services.aspx
For use of Sitecore JSS with Sitecore 10.1 and later
https://dev.sitecore.net/Downloads/~/link.aspx?_id=B5D60A30ADD1495C9B011E793AF6884F&_z=z
Enable Sitecore.Services.GraphQL.Content.Master.config and deploy to Sitecore instance
Now Try to access with https://my.sitecore.domain/sitecore/api/graph/items/master
If it shows an error message like "{"errors":[{"message":"No query was provided!"}]}" means your endpoint is working now.
You can access GarphQL Ui using: https://my.sitecore.domain/sitecore/api/graph/items/master/ui?sc_apikey={"API-Key"}
It should work fine if you notice an authentication error then here is the fix:Getting "Authentication required" error when attempting to use systemService with Sitecore GraphQL
Hope this helps!
| How do you enable `/sitecore/api/graph/items/master` endpoint in sitecore jss nextjs
I have edge graphql endpoint enabled but I noticed that it doesn't do mutations, I'm trying to figure out how to enable the built in systemContent schema for my mutation requests.
Edit
I think it's worth noting that my Sitecore environment is running on a local docker instance
Thanks in advance.
| |
This is possible by adding Rule on these individual scripts. For e.g. you can go to the below script and in its Rules section, you can add a rule as in snapshot. This will show the script only to admin users.
If you wish, you can hide the entire Scripts item in the context menu so that none of these script items are visible to content authors by going to /sitecore/content/Applications/Content Editor/Context Menues/Default/Context PowerShell Scripts and updating it security field by denying Read access to sitecore Content Author roles. This shall hide the Scripts item itself in the context menu.
There is another different approach which will hide these options in the context menu and disable any PowerShell execution altogether for content authors. This is described in - https://ghanendras.blogspot.com/2022/11/hide-context-menu-items-in-sitecore.html Please be careful if you plan to implement this as any custom implementation dependent on PowerShell script execution will get impacted by this change.
| Restricting SXA Script option for non admin Sitecore user
Is there any option to restrict non-admin Sitecore users from using the scripts option, that appears on right-clicking of tenant or site node
(Using sitecore 9.3)? Refer to the below image.
The requirement is user should not be able to delete a tenant, clone a site, or delete a site.
Thanks in advance
| |
Aside from a component having no fields, one real-world scenario that can be quite likely to occur is if the template fields aren't published, in which case you would want to do a null check on props.fields.
| Can props.fields ever be null in a Rendering Component?
I'm creating custom types for components in TypeScript (with strict null checks enabled) and I want to confirm if it makes sense to be doing null checks on props.fields, eg.:
if (!props.fields) {
return <></>;
}
A real example would be:
type myCustomProps = ComponentProps & Website.Feature.Main.MyComponent;
Where ComponentProps is the default type that ships with JSS:
export type ComponentProps = {
rendering: ComponentRendering;
params: ComponentParams;
};
And where Website.Feature.Main.MyComponent is:
export type MyComponent = {
id?: string;
url?: string;
fields: {
backgroundImage: ImageField;
}
}
In this case, I'm specifically referring to a Component Rendering. The interface that ships with JSS does seem to indicate that it's possible for the fields to be null (note the fields?), but when might that be the case?
/**
* Definition of a component instance within a placeholder on a route
*/
export interface ComponentRendering {
componentName: string;
dataSource?: string;
uid?: string;
placeholders?: PlaceholdersData;
fields?: ComponentFields;
params?: ComponentParams;
}
According to the above, Sitecore seems to be implying that the componentName can never be null, but everything else can be.
Thus far I haven't been able to find any cases in which fields is null, such as when the component is being added to a page or when a datasource is missing.
One obvious example I can think of is if the component has no fields, but in that case, a dev is highly unlikely to reference props.fields because there are none.
| |
Dean were right it was hard to catch char at AllowedCorsOriginsGroup1
| IdentityServer Invalid non-ASCII or control character in header
I have a strange issue with IdentityServer,
during redirect to IS, I see an 500 and in logs:
2022-12-08T00:04:31.7333120+00:00 [INF] (Sitecore Identity/xxxx) Route matched with "{action = \"Login\", controller = \"Account\"}". Executing controller action with signature "System.Threading.Tasks.Task`1[Microsoft.AspNetCore.Mvc.IActionResult] Login(System.String)" on controller "Sitecore.Plugin.IdentityServer.Controllers.AccountController" ("Sitecore.Plugin.IdentityServer").
2022-12-08T00:04:31.7351761+00:00 [INF] (Sitecore Identity/xxxxx) Executing action method "Sitecore.Plugin.IdentityServer.Controllers.AccountController.Login (Sitecore.Plugin.IdentityServer)" - Validation state: Valid
2022-12-08T00:04:31.7446769+00:00 [INF] (Sitecore Identity/xxxx) Executed action method "Sitecore.Plugin.IdentityServer.Controllers.AccountController.Login (Sitecore.Plugin.IdentityServer)", returned result "Microsoft.AspNetCore.Mvc.ViewResult" in 0.1069ms.
2022-12-08T00:04:31.7461571+00:00 [INF] (Sitecore Identity/xxxx) Executed action "Sitecore.Plugin.IdentityServer.Controllers.AccountController.Login (Sitecore.Plugin.IdentityServer)" in 11.7482ms
2022-12-08T00:04:31.7491966+00:00 [ERR] (Sitecore Identity/xxxx) An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Invalid non-ASCII or control character in header: 0x0009
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowInvalidHeaderCharacter(Char ch)
what could be an issue with it ?
| |
Your script looks good.
Please check the following things:
Is Boxever available? Check e.g. Boxever.browser_id in your console.
Does your POS match the one you configured in Sitecore CDP? ´
Does your cookieDomain match this: '*.yourwebsite.com'?
When you open the preview on your website, if the QA tool appears on the left, can you check that?
If it does not appear here is the trick to call it: Call your website with the missing queryparams: https://www.yourwebsite.com/?bxQATool=true&bxFlowRef=your-experience-id . The experience ID you can copy from the url when you open your experience in Sitecore CDP.
The QA tool should give you a hint, what might be wrong.
It would be good if you could share with us what you set up in Sitecore CDP.
| Sitecore Personalize Preview not working
I am working on a POC for a potential client using the sandbox that Sitecore has provided. This is for a localhost Sitecore website.
Here are the steps:
I created an alert banner that should appear at the top of the site.
I added the following code to my solution and published my code successfully. However, when I preview the site through the personalize dashboard, the alert banner does not show. What I might be missing?
<script type="text/javascript">
// Define the Boxever queue
var _boxeverq = _boxeverq || [];
// Define the Boxever settings
var _boxever_settings = {
client_key: '<<I used the key provided by Sitecore>>', // Replace with your client key
target: 'https://api-us.boxever.com/v1.2', // Replace with your API target endpoint specific to your data center region
cookie_domain: '{{cookieDomain}}', // Replace with the top level cookie domain of the website that is being integrated e.g ".example.com" and not "www.example.com"
javascriptLibraryVersion: '1.4.8', // Replace with the latest Boxever JavaScript Library version"
pointOfSale: '<<POS>>', // Replace with the same point of sale configured in system settings" (I created this POS in the Personalize System Settings)
web_flow_target: 'https://d35vb5cccm4xzp.cloudfront.net', // Replace with path for the Amazon CloudFront CDN for Sitecore Personalize"
web_flow_config: { async: false, defer: false } // Customize the async and defer script loading attributes
};
// Import the Boxever JavaScript Library asynchronously
(function() {
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = 'https://d1mj578wat5n4o.cloudfront.net/boxever-1.4.8.min.js';
var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
})();
</script>
UPDATE :
Error in the network tab: I have used the key that Sitecore provided. The same key is in the Personalize System Settings as well
{
"version": "1.2",
"status": "UNAUTHORIZED",
"error_msg": "Invalid client key specified",
"moreInfo": "mailto:[email protected]",
"clientKey": "[[Key]]"
}
| |
It is very likely to be what happened to me when applying a hotfix for 10.2. I wrote more about it here.
My interpretation of what Sitecore support conveyed in my support ticket:
The correct behavior for Federated Authentication is to allow the
Identity Provider to control the user roles. The original
implementation did not adhere to this and as such you could override
the roles assigned to users from within Sitecore.
How to fix it:
Apply custom code (as seen in my article) to restore back to previous version
Use Azure AD/ADFS to control the access through the claims.
Suffer through the issue until a hotfix for 10.3 is released.
| Roles get removed for AD login
We are using Sitecore 10.1.3 PRE. The Azure AD login is setup only for the PRD environment.
A particular user is unable to login with AD.
On login, the error says
You do not have access to the system. If you think this is wrong,
please contact the system administrator.
But on the top right of the CMS login page, the user's email is visible. The user is able to use Azure AD login successfully with other portals.
In CMS, a user is being created when logging in, but there are no roles.
When I try to add roles. The next time that user logs in, all the roles are removed.
But, for some other users in User Management, who are also using AD to login, we can see the roles.
What could be the issue here.
Will changing the value to false help? Wanted to check first before making changes in PRD and lso not to impact existing users.
<externalUserBuilder type="Sitecore.Owin.Authentication.Services.DefaultExternalUserBuilder, Sitecore.Owin.Authentication" resolve="true">
<IsPersistentUser>true</IsPersistentUser>
</externalUserBuilder>
| |
Alias should be suffixed with _internal and not with _mainalias. Make sure your alias are called xdb_internal and xdb_rebuild_internal. You can use any suffix for sitecore and use the same in the configuration but not for xdb.
Reference this link for more informaion.
You must use xdb and xdb_rebuild in your connection strings, not xdb_internal and xdb_rebuild_internal. xdb and xdb_rebuild are the default names of the primary and secondary indexes. If you change the names of the indexes, you must update all connection strings.
Also, make sure uniqueKey field has value id in xdb schema and not _uniqueid. _uniqueid is for Sitecore indexes whereas for xdb it should be id.
Example : <uniqueKey>id</uniqueKey>
| Sitecore xdb rebuild index fails at finishing stage
We are using solr cloud with zookeeper for Sitecore 10.2 environment. We have created xdb and xdb_rebuild collections with aliases xdb_mainalias and xdb_rebuildalias respectively. When we trigger xdb rebuild, it moves all the way till finishing stage (95%) and fails there. When we dig the logs it says
[Error] An error occured during index rebuilding. There will be another attempt to check. The check interval after an error is 00:00:20.
Sitecore.Xdb.Collection.Search.Solr.Failures.SolrRebuildCoreNotFoundException: Collection name for alias: [xdb_rebuild] not found in Zookeeper configuration.
at Sitecore.Xdb.Collection.Search.Solr.SolrCloudRebuildHelper.<LoadCollectionNames>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Sitecore.Xdb.Collection.Search.Solr.SolrCloudRebuildHelper.<SwapCores>d__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 Sitecore.Xdb.Collection.Search.Solr.SolrIndexRebuilder.<CompleteRebuild>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Sitecore.Xdb.Collection.Indexing.Rebuild.IndexRebuildFlow.<CompleteRebuild>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Sitecore.Xdb.Collection.Indexing.Rebuild.IndexRebuildFlow.<RunRebuild>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Sitecore.Xdb.Collection.Indexing.Rebuild.IndexRebuildFlow.RebuildStatusWatcher.<>c__DisplayClass5_0.<<Start>g__RunRebuildFlowCycle|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Sitecore.Xdb.Collection.Indexing.Rebuild.TaskExtension.<ExecuteWithInterval>d__0.MoveNext()
We have already uploaded configs to zookeeper and created xdb collections using the same. Are we missing anything here?
| |
The data stored on disk in data.json is handled differently between your two examples. In one you are using Get-Content while the other you are not. I'm pretty sure it should work in SPE for media.
Generally media items and the associated blob data is extracted with something like the following:
$item = Get-Item -Path "master:" -Id "{6AA5AA9F-071A-4808-91AC-709FAAFFB310}"
$mediaItem = [Sitecore.Data.Items.MediaItem]$item
$blobField = $mediaItem.InnerItem.Fields["blob"]
$blobField.GetBlobStream()
You could build off of this to read the stream to string using low-level .net APIs and then pass to ConvertFrom-Json. Alternatively, work with Get-Content.
Update:
Looks like it gets easier than I expected.
data.json
{
"array": [
1,
2,
3
],
"boolean": true,
"color": "gold",
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d"
},
"string": "Hello World"
}
$bytes = Get-Content -Path "master:" -ID "{74E3DA87-CECC-4568-AA16-34189F41F1EC}" -Raw
[System.Text.Encoding]::UTF8.GetString($bytes) | ConvertFrom-Json
array : {1, 2, 3}
boolean : True
color : gold
null :
number : 123
object : @{a=b; c=d}
string : Hello World
| How do you get JSON data from an item stored in the media library?
master:\media library\item-name contains a JSON file. Get-Item gets the item itself but I am unable to extract the JSON content with ConvertFrom-Json.
In PowerShell outside of Sitecore Powershell Extensions, this code works as expected:
$data = Get-Content -Raw "C:\Users\me\data.json" | ConvertFrom-Json
foreach($item in $data){
$item.name
}
When I try to use ConvertFrom-Json in Sitecore Powershell Extensions, I get a "Invalid JSON primitive" error because it's getting the item itself rather than the JSON data I uploaded:
How can I get the JSON data itself out of the item to feed to ConvertFrom-Json?
| |
To understand it very simply, Sitecore has produced a number of pre-built topologies which offer combinations of the split-out functionality:
On-premise (IaaS) topologies
Default on-premise (IaaS) topologies include:
XP Single
XP Scaled
XM Scaled
Azure (PaaS) topologies
Azure (PaaS) includes the following default topologies
XP Single
XP Scaled
XM Single
XM Scaled
You can go through this article to know more about what configurations and roles come under each topology with their diagram.
Sitecore configurations and topology for Azure
The Anatomy of Sitecore
You can download each release from the Download Portal
As you mentioned in your question that you are using XP1 instance. So here are the details of each one that you want to know more about.
Collection: The xConnect Collection service performs Receives contacts and interactions, either individually or in a batch, Allows reading of contact and interaction data by ID or identifier and Supports data extraction.
Ma: The Marketing Automation Engine role processes campaign and activity enrollments, and moves contacts through campaigns
Marketing Reporting: The Marketing Automation Reporting service allows you to retrieve plan and enrollment statistics using the Marketing Automation Reporting API
ProcessingEngine: Processing Engine service performs data processing tasks at scale
RefData: The Reference Data service allows you to create or retrieve reference data using the Reference Data Client API
Reporting: The Marketing Automation Reporting service allows you to retrieve plan and enrollment statistics using the Marketing Automation Reporting API
Search: The xConnect Collection Search service allows you to search contacts and interactions using the xConnect Client API or another API that consumes the oData service.
Here is the Sitecore documentation that you can refer to know about each role that is being used to configure a topology. It will give you all the information about the system roles or entities that can be scaled and configured in a wide variety of topologies
Roles overview
Finally, this diagram will help you to understand how they communicate with each other.
https://sitecorehacker.files.wordpress.com/2018/01/xp1-topology.png
| Uses of Different Sitecore Topologies
I am new in Sitecore and I have installed Sitecore 10.2 XP1 instance on my local machine.
I just want to know more about different roles in Sitecore topology and how they communicate with others.
Collection
Ma
Marketing Reporting
Prc
ProcessingEngine
RefData
Reporting
Search
| |
Let's assume you have the following recycling conditions:
Create a new configuration file in the Publishing Service directory, such as the following:
D:\Sites\sps\sitecoreruntime\_shared\config\sc.publishing.web.command.services.xml
Here we want to reduce the interval time to every 4 hours and reduce the retention on the job age.
<?xml version="1.0" encoding="utf-8"?>
<Settings>
<Commands>
<Web>
<Services>
<Add>
<Scheduler>
<Options>
<Tasks>
<PublishJobCleanUp>
<TaskDefinition>
<Options>
<JobAge>1.00:00:00</JobAge>
</Options>
</TaskDefinition>
<TriggerDefinitions>
<Interval>
<Options Interval="4:00:00" />
</Interval>
</TriggerDefinitions>
</PublishJobCleanUp>
<PublishOperationAgeBasedCleanUp>
<TaskDefinition>
<Options>
<PublisherOperationAge>1.00:00:00</PublisherOperationAge>
</Options>
</TaskDefinition>
<TriggerDefinitions>
<Interval>
<Options Interval="04:00:00" />
</Interval>
</TriggerDefinitions>
</PublishOperationAgeBasedCleanUp>
</Tasks>
</Options>
</Scheduler>
</Add>
</Services>
</Web>
</Commands>
</Settings>
| How do I modify the interval for cleanup tasks in Publishing Service?
We have a situation where the application pool hosting the Publishing Service is configured to restart every day at the same time (3am).
What can I do to ensure that tasks are run at least once during that window?
| |
From what I remember, Any works fine.
So if you store your specialties in List<string> or List<Guid>, you should be able to use something like:
public class SpecialtyCondition : ICondition, IContactSearchQueryFactory
{
public string Specialty { get; set; }
public bool Evaluate(IRuleExecutionContext context)
{
Contact contact = context.Fact<Contact>();
return contact.GetFacet<SpecialtyFacet>().Specialties.Any(s => s == Specialty);
}
public Expression<Func<Contact, bool>> CreateContactSearchQuery(IContactSearchQueryContext context)
{
return contact => contact.GetFacet<SpecialtyFacet>().Specialties.Any(s => s == Specialty);
}
}
public class SpecialtyFacet : Facet
{
public List<string> Specialties { get; set; }
}
| xDb: segmentation by one entry from the list
I have the following information structure that the client wants to store in the xDb user custom profile facets, it concerns the "specialty" attribute i.e:
Person 1
Gardener: oranges, apples
Person 2:
Gardener: oranges, plums, grapes
Eater: oranges
Person 3:
Eater: apples, grapes
Person 4:
-
They expect to have another "professions" which deal with fruit i.e. cook etc to be added later on. They want to be able to segment these contact lists in the following way:
select all contacts who are gardeners/eaters
select all gardeners/eaters that grow/eat apples
select all ppl (both gardeners and eaters) that deal with apples in some way
That would seem easy if I could use "contains" within the condition class, but it is not supported. Would really appreciate an idea on which facet structure could I use for this to work. Thank you!
| |
Figured out how to solve this myself so I wanted to post this in case anyone else needs help with this. I realized that the FieldItems are just xml so I created a new ImageField and then added the attributes that I needed.
new ImageField(this.providerItem.Fields["Image"])
{
Alt = this.ProviderName,
LinkType = "external",
Height = Height.ToString(),
Width = Width.ToString()
};
ImageField imageField = (this.providerItem.Fields["Image"]);
imageField.SetAttribute("stylelabs-content-id", this.Entity.Entity.Id.ToString());
imageField.SetAttribute("thumbnailsrc", "https://contenthub-url/api/gateway/" + img.Id.ToString() + "/thumbnail");
imageField.SetAttribute("src", img.PublicLinkUrl);
imageField.SetAttribute("mediaid", "");
imageField.SetAttribute("stylelabs-content-type", "Image");
this.providerItem.Editing.EndEdit();
| Update Sitecore ImageField with Media Item from Content Hub
I'm writing a program that creates a new asset in Content Hub using the upload API. How do I attach that newly created asset to theImageField of an item in Sitecore. Most of the examples show how to create a new ImageField item using something from the media library but I haven't found anything using Content Hub. Here's the basics of what I've got so far which obviously doesn't work but it illustrates what I'm trying to accomplish:
using (new SecurityDisabler())
{
var providerItem= db.GetItem(this.SiteCorePath);
if (providerItem.Empty) return false;
this.providerItem.Fields.ReadAll();
this.providerItem.Editing.BeginEdit();
try
{
this.providerItem.Fields["SelectHealth Image"].Value = this.PublicUrl;
this.providerItem.Editing.EndEdit();
}
catch
{
this.providerItem.Editing.CancelEdit();
return false;
}
}
| |
The statement in the Sitecore documentation is somewhat misleading. Publishing your content to Experience Edge does NOT expose that content to the public. The Experience Edge endpoint requires an API Key/secret to get content and that API Key/secret should never be exposed to the public. Do not ever directly call the Experience Edge end point from client-side code, obfuscate this behind an API.
The users and roles in the Sitecore CM, should never be used to provide logins to your delivered website. This has been done many times in the non-headless world, but it is a bad practice and leads to user stores that do not scale well and can make it harder to administer your CM users too.
You should keep your authentication for your CM users separate from your website users.
For headless applications, your head application (Next.js/React/ASP.NET Core etc...) is entirely responsible for securing any part of your website. Each framework has ways of doing this so I will cover principles here vs concrete examples. But in general, you can explicitly secure parts of your website via hard coded methods, or you can use data from the CM to decide how to secure that data.
You should use an auth provider to provide authentication/roles etc.. (e.g. Auth0, (Firebase)[https://firebase.google.com/] etc...) and integrate that with your application.
If you want to control what is/isn't visible to users, you can easily create a field on your page templates to identify who can see that page to your head application. But its up to the head application to obey those rules.
| How should security be handled for XM Cloud/Headless with Experience Edge?
In the Sitecore documentation for Experience Edge (used by XM Cloud), it states:
Experience Edge for XM does not enforce security constraints on Sitecore content. You must apply publishing restrictions to avoid publishing content that you do not want to be publicly accessible - Limitations & Restrictions of Experience Edge for XM
In Sitecore MVC, we could add security roles to page items and the pages would only show for logged in users that matched those roles. How can we achieve this in Headless with Experience Edge?
| |
Sitecore has provided these options in the Sitecore.Client DLL. When I extracted it I found the code under the class Sitecore.Shell.Applications.Install.Controls.BehaviourOptionEditor where it is setting the default values like this.
protected virtual void SetValue(BehaviourOptions value)
{
InstallMode itemMode = value.ItemMode;
this.OverwriteItems.Checked = false;
this.OverwriteItems.Checked = itemMode == InstallMode.Overwrite;
this.MergeItems.Checked = false;
this.MergeItems.Checked = itemMode == InstallMode.Merge;
this.SideBySideItems.Checked = false;
this.SideBySideItems.Checked = itemMode == InstallMode.SideBySide;
this.SkipItems.Checked = false;
this.SkipItems.Checked = itemMode == InstallMode.Skip;
this.AskUser.Checked = false;
this.AskUser.Checked = itemMode == InstallMode.Undefined;
if (!this.MergeOption)
return;
this.SelectListItem(((int) value.ItemMergeMode).ToString(), this.MergeOptions);
this.MergeOptions.Disabled = !this.MergeItems.Checked;
}
And here you can find the default descriptions.
private void ShowHint(BehaviourOptions value)
{
switch (value.ItemMode)
{
case InstallMode.Undefined:
this.messageText = this.User != PackageUser.Developer ? Translate.Text("Choose any option to view option description.") : Translate.Text("If files with the same ID or Path are found, you will be asked to resolve the conflict.");
break;
case InstallMode.Overwrite:
this.messageText = Translate.Text("Replace the entire subtree with the subtree in the package.");
break;
case InstallMode.Merge:
StringBuilder stringBuilder = new StringBuilder();
switch (value.ItemMergeMode)
{
case MergeMode.Undefined:
stringBuilder.Append(Translate.Text("Undefined."));
break;
case MergeMode.Clear:
stringBuilder.Append(Translate.Text("Leave the subtree and replace any matching items and versions with those from the package but do not replace any subitems."));
break;
case MergeMode.Append:
stringBuilder.Append(Translate.Text("Leave the subtree. Overwrite nothing. Append any matching item versions to the existing subtree by giving them incremental numbers."));
break;
case MergeMode.Merge:
stringBuilder.Append(Translate.Text("Leave the subtree and replace any matching items and versions with those from the package."));
break;
}
this.messageText = stringBuilder.ToString();
break;
case InstallMode.Skip:
this.messageText = Translate.Text("Take no action and move on to the next item.");
break;
case InstallMode.SideBySide:
this.messageText = Translate.Text("Install second item from the package without touching any existing items.");
break;
}
this.BehaviorOptionText.Text = this.messageText.ToString();
}
You will find the XML in this location.
wwwroot\<your-site-root>\sitecore\shell\Applications\Install\Dialogs\Install package
And the reference of this class can be found in this XML.
wwwroot\<your-site-root>\sitecore\shell\Applications\Install\Controls\BehaviourOptionEditor.xml
You can update and replace the XML with your own class here.
I hope this is enough information to get started.
Thanks.
| How to set default merge options on package installation
When we install a package and there is an existing item, we see this message:
I would like to
Keep the Merge > Append selected as default.
Change the existing description text for each option.
I see this URL in the browser console - /sitecore/shell/Applications/Tools/Installer*/InstallationWizard
But could not find the Installer folder in my local instance.
Is this possible. How to go about it.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.