output
stringlengths 34
25.7k
| instruction
stringlengths 81
31k
| input
stringclasses 1
value |
---|---|---|
Instead of calling
Item createdItem = Event.ExtractParameter(args, 0) as Item;
use the following code:
ItemCreatedEventArgs itemCreatedEventArgs = Event.ExtractParameter<ItemCreatedEventArgs>(args, 0);
var createdItem = itemCreatedEventArgs.Item;
OnItemSaving and OnItemSaved methods are executed twice because of how Sitecore works:
first item is created only with name and template - that's then first set of events is triggered
then other item fields are set - that's when events are triggered again.
|
item:save events are triggered twice when an item is created
I'm trying to log item events like - on item created, on item saved etc.
patch.config:
<events>
<event name="item:created">
<handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemCreated"/>
</event>
<event name="item:saving">
<handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemSaving"/>
</event>
<event name="item:saved">
<handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemSaved"/>
</event>
</events>
ItemEventHandler.cs:
public class ItemEventHandler
{
public void OnItemCreated(object sender, EventArgs args)
{
Item createdItem = Event.ExtractParameter(args, 0) as Item;
if (createdItem == null)
return;
Log.Info("ITEM CREATED");
}
public void OnItemSaving(object sender, EventArgs args)
{
Item changedItem = Event.ExtractParameter(args, 0) as Item;
if (changedItem == null)
return;
Log.Info("ITEM SAVING");
}
public void OnItemSaved(object sender, EventArgs args)
{
Item changedItem = Event.ExtractParameter(args, 0) as Item;
if (changedItem == null)
return;
Log.Info("ITEM SAVED");
}
}
There are 2 issues here:
In the OnItemCreated method, the createdItem is always null. But in quick watch, I can see the created item.
And so, the Log.Info method is never getting executed here.
After the OnItemCreated, the OnItemSaving method is triggered and then the OnItemSaved. Both the save methods get the item data. But these two methods are triggered twice.
So, the logs are like:
2023-07-04 10:00:01 ITEM SAVING
2023-07-04 10:00:02 ITEM SAVED
2023-07-04 10:00:03 ITEM SAVING
2023-07-04 10:00:04 ITEM SAVED
| |
item:saving event is executed before item is saved in the database.
Item which is stored within event args is what will be saved to the database if none of the handlers abandons the process.
And item which is in the database is the original one as nothing was saved to database yet. When you're calling
Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);
you're telling Sitecore to give you what is there still in the database before you "confirm" or "cancel" saving new changes.
So yes, in your case newItem has all the new field values and originalItem has all the fields which are still in the database.
With that approach you can add some condition when item should not be saved to the database and call the following line in order to prevent saving new values:
ItemSavingEventArgs itemSavingEventArgs = (ItemSavingEventArgs) args;
itemSavingEventArgs.Cancel = true;
|
item:saving event has both new and old field values
I have followed this example and here is my custom event handler for item:saving.
protected void OnItemSaving(object sender, EventArgs args)
{
Item newItem = Event.ExtractParameter(args, 0) as Item;
Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);
string Title = originalItem.Fields["Title"].Value; // "Chapter One" (old value)
Title = newItem.Fields["Title"].Value; // "Chapter Two" (new value)
}
The code works perfect for my requirement, but I'm confused on a few things.
I was assuming that the Item fetched in the item:saving event will only have old field values, but here the newItem has new values also.
I'm unable to understand this piece of code on how it is getting old item/old values from newItem -
newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);
Could anyone please help me understand. Thank you.
| |
There are several ways to do it -
Email to Global Sitecore Training [email protected]
Open a Sitecore Support Ticket on Learning@Sitecore Support Case. For this follow - https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1000647
Chat online on Webassessor chat support.
|
Reschedule Sitecore Certification Exam after time has passed
I was not able to start the Sitecore Certification exam on time due to some reason, and time has passed.
Now, I want to reschedule the Sitecore Certification Exam. How can I do it?
| |
role and env is used in order to allow a rule-based configuration. This allow you to set configuration specific for given role or for given environment without a need to deploying different files to every separate Sitecore role or environment.
Full documentation can be found here: https://doc.sitecore.com/xp/en/developers/103/platform-administration-and-architecture/use-a-rule-based-configuration.html
For the role:require attribute you should use one (or more) of Sitecore roles which are:
ContentDelivery
ContentManagement
Processing
Reporting
Standalone
In theory the setting will allow any other texts but I cannot think of any real live use case when you may need it.
More about roles can be found here: https://doc.sitecore.com/xp/en/developers/103/platform-administration-and-architecture/define-the-server-role.html
Those 2 setting means that if in web:config there will be setting:
sourceFolder variable will be set to D:\project\src. And if there will be any of dev, qa or prod in web.config, value of the variable will be set to /App_Data/unicorn.
More to be read here: https://doc.sitecore.com/xp/en/developers/103/platform-administration-and-architecture/add-a-custom-rule-to-your-configuration.html
|
VariableSerialization.config Custom Config file
Hope you all are well. I am new in Sitecore. So,I have few queries to clear my doubts. I have shared a picture which is a part of config file.
In the picture why we used xmlns:role and xmlns:env ?
Inside the role:require attribute can I set any random text like demo/test or I need to set the predefined text like Standalone or ContentManagement ?
Inside the env:require attribute I can see there are two value set for two different parts. What is the meaning of env:require="user" and env:require="dev or qa or prod" ?
| |
You cannot pass data between Sitecore events. Sitecore events you mention in your question are built-in events and you should not raise them on your own in your custom code.
From this and other question asked by you recently, I think you should change your approach slightly instead of passing data between events.
If you want to audit changes in Sitecore using custom code, maybe the following approach would work for you:
on item:created - audit only information about item name, id, location and tempalte
on item:saving - audit only changed fields. Make sure that your event handler is last one in the config, check if args.Cancel is not true and use code similar to:
protected void OnItemSaving(object sender, EventArgs args)
{
var itemSavingEventArgs = args as ItemSavingEventArgs;
if (itemSavingEventArgs != null && !itemSavingEventArgs.Cancel)
{
var itemChanges = itemSavingEventArgs.Changes;
DoSomethingWithItemChanges(itemChanges);
}
}
on item:saved you can confirm that item:saving was completed but don't audit any changes anymore.
|
How to pass custom data between Sitecore events
I would like to pass an object from the item:created event to the item:saving event, but unable to do so.
This is to add custom logs for certain events. When an item is created, I will be logging the event in the OnItemCreated method. But this will also trigger the OnItemSaving & OnitemSaved methods, where I do not want to log for item creation as there is one log already.
patch.config:
<events>
<event name="item:created">
<handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemCreated"/>
</event>
<event name="item:saving">
<handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemSaving"/>
</event>
</events>
ItemEventHandler.cs:
protected void OnItemCreated(object sender, EventArgs args)
{
ItemCreatedEventArgs itemCreatedEventArgs = Event.ExtractParameter<ItemCreatedEventArgs>(args, 0);
Item createdItem = itemCreatedEventArgs?.Item;
///Pass object to successor event
MyClass obj = new MyClass();
Event.RaiseEvent("item:saving", new object[] { createdItem, obj });
}
protected void OnItemSaving(object sender, EventArgs args)
{
Item changingItem = Event.ExtractParameter(args, 0) as Item;
MyClass obj = Event.ExtractParameter(args, 1) as MyClass; //Here obj is always null
MyClass obj2 = new MyClass();
///Pass obj to successor event
Event.RaiseEvent("item:saved", new object[] { changingItem, obj2 }); //Here is an exception
}
Exception:
could not extract parameter from event args
| |
After investigation, I get to know that, This Security Hotfix might add a security layer that prevents the execution of unexpected methods through reflection.
As I have customized the publishing method for Sitecore items, I am getting this issue while publishing the Sitecore items.
Solution:
Go to the path \App_Config\Sitecore\CMS.Core\ and open the
Sitecore.Reflection.Filtering.config file.
Add the method name to
the Sitecore.Reflection.Filtering.config file:
<allowedMethods>
<!--Example:
<descriptor type="SampleNameSpace.MyClass" methodName="MyMethod" assemblyName="MyAssembly"/>
-->
<!--your allowed methods-->
<descriptor type="{assemblyName}.sitecore.shell.Applications.Dialogs.Publish.PublishForm" methodName="StartPublisher" assemblyName="{assemblyName}"/>
</allowedMethods>
Add a method pattern to the Sitecore.Reflection.Filtering.config file:
<allowedPatterns>
<pattern value="^Sitecore\..*,Sitecore\..*$"/>
<!--your allowed patterns-->
<pattern value="^{solutionName}\..*,{solutionName}\..*$"/>
</allowedPatterns>
Where the value is a regular expression matched against the method name string in the format NameSpace.Class.Method, AssemblyName.
See the blog post for more details: Error: Method Through Reflection is Not Allowed after Applying Sitecore Hotfix
|
Method Through Reflection is Not Allowed after Applying Sitecore Hotfix
I have applied the recent hotfix from Sitecore security bulletin SC2023-003-587441 in my solution and deployed it, but I am getting the following error while publishing the Sitecore Items.
Server Error in '/' Application.
Calling *********.****.sitecore.shell.Applications.Dialogs.Publish.PublishForm.StartPublisher method through reflection is not allowed.
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: Sitecore.Exceptions.AccessDeniedException: Calling *********.****.sitecore.shell.Applications.Dialogs.Publish.PublishForm.StartPublisher method through reflection is not allowed.
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:
[AccessDeniedException: Calling *********.****.sitecore.shell.Applications.Dialogs.Publish.PublishForm.StartPublisher method through reflection is not allowed.]
Sitecore.Reflection.MethodFilter.Filter(MethodInfo method) +1167
Sitecore.Shell.Framework.Commands.CommandManager.GetMethodCommand(String command) +701
Sitecore.Web.UI.Sheer.ClientPage.Dispatch(String command) +35
Sitecore.Web.UI.Sheer.ClientPage.RaiseEvent() +144
Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e) +806
System.Web.UI.Control.PreRenderRecursiveInternal() +200
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +7479
| |
The first step would be to create a custom script in one of your modules.
For example, create a custom SPE module using the wizard followed by whatever library structure you prefer. Check out the official SPE docs for additional details.
Show-Alert -Title "Hello!"
Close-Window # Causes the runner dialog to close automatically
Copy the item ID of the script.
Switch to the core database and create a new menu item. For the demo we'll create it at the following path:
# Item path
/sitecore/content/Applications/Content Editor/Context Menues/Default/Say Hello
The Message field should contain the following where the script parameter matches the item ID of the script.
item:executescript(id=$Target,script={5BCE1B7C-E484-4809-B34F-C1F2B65905DD}, scriptDb=master)
Switch back to the master database and give the new menu item a try.
Note: Big thanks to Kurt Bilde for asking about it on Sitecore Chat.
|
How do you add a custom context menu to run an SPE script not in the scripts section?
I would like to have a custom context menu like the following:
Since this menu item does not follow the typical integration points for SPE, how would I go about making it work with a script?
| |
Unfortunately the answer to your question is "No, Sitecore did not take this scenario into account".
If you look at the Sitecore.Data.Fields.DelimitedField field class, Relink method simply replaces original item ID with new item ID:
public override void Relink(ItemLink itemLink, Sitecore.Data.Items.Item newLink)
{
string str = itemLink.TargetItemID.ToString();
if (!this.Contains(str))
return;
this.Replace(str, newLink.ID.ToString());
}
It doesn't check for duplicates.
I think the warning message in the popup before relinking could be helpful but could be also confusing for content authors.
In theory nothing stops you from creating your own class inheriting from Sitecore.Data.Fields.MultilistField and overriding method
public override void Relink(ItemLink itemLink, Sitecore.Data.Items.Item newLink)
checking for uniqueness and applying the logic you want there. And then registering instead of
<fieldType name="Checklist" type="Sitecore.Data.Fields.MultilistField,Sitecore.Kernel" resizable="true"/>
your own field type implementation
<fieldType name="Checklist" type="MyAssembly.MyNamespace.MyCustomChecklistField,MyAssembly" resizable="true"/>
But I haven't heard about anyone who had done it so you would have to be really careful and thorough while testing if nothing was broken with that change.
|
Duplicate selected IDs appearing in raw value of checklist field after deleting an item and linking to other (already selected) item
I ran into an issue when cleaning up two pairs of items like so:
Parent item
Reference Item 1
Similar Reference Item 1 [delete and relink to Reference Item 1]
Reference Item 2
Similar Reference Item 2 [delete and relink to Reference Item 2]
The above items are part of a list of items which are used as options for a checklist field; specifically, a list of timezone items which are the source for a checklist field on an event item.
Prior to the cleanup, I had an event item that had all of the timezone options selected. The image below is what that checklist field looks like after performing the cleanup. Notice how the last two options say [Not in the selection List] and that they are already selected as the 3rd and 4th options. After inspecting the raw value of the field, I can see that those two IDs are in fact selected twice. Normally, the UI wouldn't let you selected the same option twice in a multilist-type field, so this is a problem:
It seems that relinking during item deletion does not take into account if the field we are updating is already also referencing the item that we are relinking to.
That is, prior to the cleanup, the event would have had these options selected in the checklist field:
Reference Item 1
Similar Reference Item 1
Reference Item 2
Similar Reference Item 2
And after performing the relinks, we wound up with this:
Reference Item 1
Reference Item 1
Reference Item 2
Reference Item 2
Note that I don't have the option of removing the breaking links (instead of updating) during deletion because it's not always guaranteed that event items will be referencing both items in a set. Whether an event was previously linking to one or both of the options in the set, it always needs to result in there being a single link to the remaining item, e.g. when Reference Item 1 or Similar Reference Item 1 or both are selected, the end result should be that Reference Item 1 is the only selected option.
Does Sitecore not take this scenario into account when relinking? I can understand why it wouldn't, because Sitecore can't make assumptions about what the order of the selected options should be. If merging two IDs into one, which one should be removed? That's not Sitecore's call. Therefore, it keeps both in their respective places and simply updates the ID(s). Then again, in the case of a checklist field, the selected options aren't able to be re-ordered like a true multilist field, so I wouldn't expect to see this problem for checklist fields.
Further, if this observation is correct, isn't the implication that we should be performing a uniqueness check whenever we enumerate multilist-type fields?
What are my options? It seems that the instances of the issue would need to be resolved case by case or via a script. Either way, it would have been helpful if a dialog box warned me that this was going to happen.
| |
You first need to find the ancestor or self item which is not in web database yet and then publish it with subitems.
Remember to check if the media item is not there already - this may happen if folder containing that item was already published with subitems while publishing another media item:
public void PublishMediaItemsAndTheirFolders()
{
List<MediaItem> createdMediaItems = UploadMediaItems();
var targetDatabase = Database.GetDatabase("web");
foreach (var createdMediaItem in createdMediaItems)
{
Item itemToBePublished = FindNotPublishedAncestorOrSelf(createdMediaItem.InnerItem, targetDatabase);
if (itemToBePublished != null)
{
var handle = PublishManager.PublishItem(itemToBePublished, new[] {targetDatabase}, new[] {itemToBePublished.Language}, true, false, false);
// wait 3 minutes - if publishing job takes longer, it will process in the background
PublishManager.WaitFor(handle, 3 * 60 * 1000, 100);
}
}
}
private Item FindNotPublishedAncestorOrSelf(Item item, Database targetDatabase)
{
// this may happen if item was already published when publishing parent folder
if (targetDatabase.GetItem(item.ID, item.Language, item.Version)?.Statistics.Revision == item.Statistics.Revision)
return null;
// parent already is in web database - it's enough to publish item itself
if (targetDatabase.GetItem(item.ParentID) != null)
return item;
// parent not in web database yet - check if parent of the parent is there already
return FindNotPublishedAncestorOrSelf(item.Parent, targetDatabase);
}
|
Programmatically publish of media items
I have a requirement in a project where a service is automatically creating media items in sitecore media library in a random folder structure. I want to publish the media items once they are created. Once media item is created, I have the media id and path to do the publish but, how to automatically publish all the parent folders as well which are also created in the process.
Like my folder structure can be like below :
/sitecore/Media Library/Media/Images/Image1
/sitecore/Media Library/Media/Image2
/sitecore/Media Library/Media/PDF/Pdf1
| |
Seems like the issue is due to the absence of an escape character in the script. In the docker-compose.override.yml file located at docker-examples/custom-images/docker-compose.override.yml, the entry point for the CM node specifies the command as entrypoint: powershell -Command "& C:\\tools\\entrypoints\\iis\\Development.ps1".
In PowerShell, the ampersand (&) is used to invoke a script or command. However, the backslash (\) is an escape character in YAML syntax. To ensure that the backslashes are interpreted correctly and treated as literal characters when executing the PowerShell command, they need to be properly escaped.
To resolve this issue, make sure you include the necessary escape characters when running the script. Here's an example of how the command should be executed:
powershell -Command "& \"C:\\tools\\entrypoints\\iis\\Development.ps1\""
By adding double quotes (") around the script path and escaping each backslash with another backslash, you ensure that the PowerShell command correctly recognizes the path.
Please give this modified command a try and see if it resolves the problem you encountered while spinning up the CM instance in Docker.
|
CM instance error | Sitecore in Docker
I was trying to run Sitecore in Docker and was following the document at https://github.com/Sitecore/docker-examples.
It broke while spinning up the CM instance. The error I received is the following:
the term 'c:toolsentryendpointsiisdevelopment.ps1' is not recognized
I checked everything including my steps, Google and Bing search. I am unable to understand where it is going wrong.
In case it matters, the set-up is in a nested VM.
| |
You will need to create a custom command and invoke it on button click.
This command should be registered through patch. Here is one old article but it should give you some clue.
Edit Frame with custom command
If you can decompile SXA assemblies, do check Sitecore.XA.Foundation.Editing.Commands namespace. This is helpful.
Btw, as you need to read user input in EE, you can also think of using rendering parameter. Since it is a native feature of Sitecore, it can be easily implemented. You can simply educate your content authors how to edit it. Also, if you want to restrict user, you can create parameter template and associate it with rendering. Here are some examples -
https://www.logicalfeed.com/posts/114/rendering-parameters-in-sitecore-with-example
Rendering Parameter Template
|
Need guidance on implementing a custom Webedit button in Experience Editor with a popup for user input
I'm developing a custom Webedit button for Sitecore Experience Editor. The goal is to display a popup in the Experience Editor when the button is clicked and retrieve user input from the popup. Currently, I have successfully created the /sitecore/content/Applications/WebEdit/Common Field Buttons Webedit button from Core database, and it is visible in the Experience Editor. I'm seeking guidance on implementing this functionality and would greatly appreciate it if someone could provide me with some references.
Thank you in advance.
| |
You should be careful with making too many assumptions around the PublishingAPI, it has undergone a lot of changes in recent months and years.
Anyway, that said. "Full" and "Smart" are both "Full Publishes", but the "compareRevisions" flag will be false for a "Full" publish, and true for a "Smart" publish.
|
When doing a Smart Site Publish, the PublishContext.PublishOptions.Mode is "Full" instead of "Smart"
When I perform a Site Publish, there are 3 options - Incremental publish, Smart publish & Republish.
I'm capturing the PublishMode in a custom Handler and the results are:
For Incremental publish - Incremental
For Smart publish - Full
For Republish - Full
I'm expecting that the PublishMode would be Smart for the Smart publish instead of Full. Is that correct?
Using v10.3
patch.config:
<pipelines>
<publish>
<processor type="MyCode.Handlers.AuditPublish, MyCode"/>
</publish>
</pipelines>
AuditPublish.cs
public class AuditPublish:PublishProcessor
{
public override void Process(PublishContext context)
{
var mode = context.PublishOptions.Mode.ToString();
}
}
| |
You may encounter a similar issue when the container is spun up using the up.ps1 script, and subsequently, when attempting to run docker compose down followed by docker compose up, you encounter an error. This issue is likely caused by the network interface created by up.ps1 not being properly utilized during the execution of docker compose up.
To resolve this problem, follow these steps:
Run docker network ls to list all the available networks.
Run docker network prune to remove all networks.
Note: This command will delete all unused networks on your system.
If you want to remove specific network use the command docker network rm <network Id> <space> <network Id> to remove the problematic network.
Once the network pruning is complete, run docker compose up -d to start the containers.
After following these steps, the issue should be resolved, and docker compose up should work fine.
Reference:
https://docs.docker.com/engine/reference/commandline/network_prune/
https://docs.docker.com/engine/reference/commandline/network_ls/
|
docker containers do not start - network was found but has incorrect label com.docker.compose.network set to ""
The messages are warning... but i cannot get the endpoints... any ideas ?
level=warning msg="The \"H\" variable is not set. Defaulting to a blank string."
At line:1 char:1
+ docker-compose up -d
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (time="2023-07-1... blank string.":String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
level=warning msg="The \"H\" variable is not set. Defaulting to a blank string."
level=warning msg="The \"H\" variable is not set. Defaulting to a blank string."
level=warning msg="a network with name tac_default exists but was not created by compose.\nSet `external: true` to use an existing
network"
network tac_default was found but has incorrect label com.docker.compose.network set to ""
| |
I had the same issue and found the solution, at least on my instance.
I followed what Dean mentioned in his answer, and I had all that in place but it still didn't work. Then I remembered some time ago there was a Sitecore Support package, where we had to manually delete xaml handlers from Sitecore.config. We were supposed to do it only on CD, but we did it on CM as well by accident.
So all I did was add back the custom handlers on CM's Sitecore.config:
<customHandlers>
...
<handler trigger="-/xaml/" handler="sitecore_xaml.ashx"/>
<handler trigger="~/xaml/" handler="sitecore_xaml.ashx"/>
...
</customHandlers>
|
On Sitecore Item, when we click on Folder tab, The requested document was not found
Currently using Sitecore 10.2 XM version, when clicking on the folder tab on folder item there is an error showing as below.
Attaching log stack trace
ManagedPoolThread #8 20:22:56 INFO Job started: Index_Update_IndexName=Coveo_master_index
ManagedPoolThread #8 20:22:56 ERROR Exception
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.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj)
at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args)
at (Object , Object )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
at Sitecore.Jobs.DefaultJob.DoExecute()
at Sitecore.Abstractions.BaseJob.ThreadEntry(Object state)
Nested Exception
Exception: System.ArgumentNullException
Message: Precondition failed: The parameter 'p_Communication' must not be null
Parameter name: p_Communication
Source: Coveo.Framework
at Coveo.Framework.CNL.Precondition.NotNull(Object p_Parameter, String p_ParameterName)
at Coveo.SearchProvider.AbstractProviderUpdateContext..ctor(ISearchIndexSummary p_IndexSummary, IIndexCommunication p_Communication)
at Coveo.SearchProvider.ProviderUpdateContext..ctor(ISearchIndex p_Index, IIndexCommunication p_Communication)
at Coveo.SearchProvider.ProviderIndex.CreateUpdateContext()
at Coveo.SearchProvider.ProviderIndex.Update(IEnumerable`1 p_IndexableInfo)
Any suggestions here, to fix the issue?
| |
When you run an A/B – or multivariate test, Sitecore will assess its success based on the trailing value/visit, which is the average collected engagement value after being exposed to the test. The logic behind this is: If there is a significant engagement value difference between the variations of your content, it can be attributed to the content the visitors see.
The engagement value is an integer that aggregates for each contact over time. The most common way of increasing the engagement value is to create a goal in Sitecore and assign it to an action, like visiting a certain page or submitting a form. The engagement value of a contact tells you how valuable this contact is for your organization, while the value per visit (= average change in engagement value per website visit) tells you how successful your website is in achieving your business goals.
So in your case, it measures the First Page Submission goal is a top converted goal during the test period and it got highrer converstion and engegement value then other goals.
Take a look this for better understanding.
Hope it helps!
|
A/B testing is showing a change of 42% in Top Goal Converted. How Sitecore calculate this change value?
I implemented A/B testing in Sitecore 10.1.2. Now we are getting a result of Top Goal Converter. Now I am not able to understand how this Change value 42% is calculated, please check the image below. The goal it is referring, is new and created for this test only.
I checked below URL form Sitecore and from there it means the change between the original experience and the selected experience.
https://doc.sitecore.com/xp/en/users/101/sitecore-experience-platform/content-test-results.html
Can anyone please help me to understand how Sitecore is calculating the value?
| |
If you see the code for the Edit User Dialogue from the User Manager, here is the location of the file in the Sitecore webroot.
inetpub\wwwroot\<your application root>\sitecore\shell\Applications\Security\EditUser\EditUser.xaml.xml
This file refers to the DLL i.e. Sitecore.Client and the event is written in this class Sitecore.Shell.Applications.Security.EditUser.EditUserPage. And here is the code snippet to add Edit User or Role.
protected override void OK_Click()
{
if (!this.Validate() || !this.ValidateTicket())
return;
User user = EditUserPage.GetUser();
Assert.IsNotNull((object) user, typeof (User), "User not found");
UserProfile profile = user.Profile;
Assert.IsNotNull((object) profile, typeof (UserProfile));
try
{
IEnumerable<Role> roles = this.Roles.Items.Cast<System.Web.UI.WebControls.ListItem>().Where<System.Web.UI.WebControls.ListItem>((Func<System.Web.UI.WebControls.ListItem, bool>) (item => System.Web.Security.Roles.RoleExists(item.Value))).Select<System.Web.UI.WebControls.ListItem, Role>((Func<System.Web.UI.WebControls.ListItem, Role>) (item => Role.FromName(item.Value)));
HttpContext current = HttpContext.Current;
Assert.IsNotNull((object) current, typeof (HttpContext));
string controlValue = string.Empty;
foreach (string key in current.Request.Form.Keys)
{
if (key != null && key.EndsWith("StartUrlSelector", StringComparison.InvariantCulture))
{
controlValue = current.Request.Form[key];
break;
}
}
if (controlValue == "Default")
controlValue = string.Empty;
if (controlValue == "Custom")
controlValue = this.StartUrl.Text;
user.Roles.Replace(roles);
....
....
}
So you can override this class and replace it in the XML file to use your logic.
You can also try this with an Update event like this.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<events>
<event name="user:updated">
<handler type="Custom.UserUpdatedEventHandler, Custom" method="OnUserUpdated"/>
</event>
<event name="user:updated:remote">
<handler type="Custom.UserUpdatedEventHandler, Custom" method="OnUserUpdatedRemote"/>
</event>
</events>
</sitecore>
</configuration>
See this thread for more details.
How to send email, when users roles change - User Manager customization
I hope this will help.
|
Which event to extend when a role is added to user
I would like to log when a role is added or removed for a user.
But none of these methods are being triggered on such use cases.
patch.config:
<sitecore>
<events>
<event name="roles:usersAdded">
<handler type="MyCode.AccountEventHandler, MyCode" method="OnRoleAddedForUser"/>
</event>
<event name="roles:usersRemoved">
<handler type="MyCode.AccountEventHandler, MyCode" method="OnRoleRemovedForUser"/>
</event>
<event name="user:runtimerolesupdated">
<handler type="MyCode.AccountEventHandler, MyCode" method="OnUserRuntimeRolesUpdated"/>
</event>
<event name="user:updated">
<handler type="MyCode.AccountEventHandler, MyCode" method="OnUserUpdated"/>
</event>
</events>
</sitecore>
AccountEventHandler.cs
protected void OnRoleAddedForUser(object sender, EventArgs args)
{
Log.Info("Role added for user");
}
protected void OnRoleRemovedForUser(object sender, EventArgs args)
{
Log.Info("Role removed for user");
}
protected void OnUserRuntimeRolesUpdated(object sender, EventArgs args)
{
Log.Info("Role updated for user");
}
protected void OnUserUpdated(object sender, EventArgs args)
{
Log.Info("user updated");
}
I have extended other events like user:created & user:deleted. They work fine.
| |
I am uncertain whether the Acquia Drupal Connector is currently outdated. I suggest that you can check with Sitecore Support/Sales for confirming.
Other than that, there is indeed another approach to link Drupal with Sitecore Content Hub.
Please kindly find this link Drupal Connector for your reference.
And the Drupal related plugins mentioned in the post can be obtained from Iframedialog & Mconnector.
This zip package extends CKEditor for use in creating content in Drupal by providing approved assets in an iFrame, thereby integrating with the Sitecore Content Hub. This extension is implemented through a module and plugin library.
Seems there is only Japanese edition of this current post.
While you can read and follow it with some online translating tools or browswer extension, like Immersive Translate.
Also I listed the key steps for your reference.
Installation steps:
Download and unzip the zip package containing the two plugins Iframedialog & Mconnector, and copy the libraries and modules folders to the root directory of Drupal.
Enable the two plugins in Drupal backend.
In the configuration page, add a new toolbar group "Sitecore Plugin" containing Sitecore icon to the CKEditor editor.
Fill in the URL of Sitecore Content Hub in MConnector Settings.
Add Drupal's URL to CORSConfiguration in PortalConfiguration in Sitecore backend.
Usage:
In Drupal, click Add Content, choose Basic page, and click the icon in Sitecore plugin group to select assets from Sitecore.
Click the arrow icon of the asset to create or choose a public link, then click "Select" to import the asset into Drupal.
And Sitecor Connect is a new SAAS DXP product which neede a new licensing, I think.
If you would like to get more info of Sitecore Connect, please try to leave a messag at the bottom form in Sitecore Connect Product or chat with the Sitecore consultant online, and the expert would further help.
Hope it helps!
|
Content Hub Connector for Drupal
I have been searching for a connector that will link up Content Hub to Drupal. I found a page in Marketplace, but the links seem to be missing from it so I'm assuming it may be outdated (https://www.sitecore.com/products/marketplace/tap/ch/acquia-drupal-connector). There was a video about it on YouTube, but it's in Japanese unfortunately.
My question is - is there a way to connect Sitecore Content Hub to Drupal the way that it connects to the Sitecore CMS? Is Sitecore Connect the tool to use? If so, does that require a separate license? If not, is there just a generic connector? The info I'm finding online isn't very specific.
This link mentions Drupal, but doesn't indicate which connector to use: https://doc.sitecore.com/ch/en/users/42/content-hub/integrate-with-sitecore--focus-on-integration.html
| |
You can see that the title of the field is
Scope query [shared]
Shared field means that its value is shared across all language versions. You cannot select different values for EN and for IT versions of that page.
What you can do though is using predefined SXA token CurrentLanguage in Query Builder as explained in Sitecore documentation:
https://doc.sitecore.com/xp/en/users/sxa/101/sitecore-experience-accelerator/extend-search.html
|
Saving one language version of search scope item overwrites other languages versions of same item
I am working on a multilingual site in Sitecore and I need to filter search results by current language.
I am using a search scope and I would like to have different versions of a search scope, one for each language.
In the english version of the scope, I added +language:en to the Scope Query field.
Then I switched to italian version of the scope and changed the Scope Query field to +language:italian_italy.
It turns out that the english version of the scope was overwritten too, so in the Scope Query of the english version now I have +language:italian_italy! So currently I am not able to have different Scope query field values for different languages' versions of the same search scope item.
Am I missing something? Is there a way to make it work or will I be forced to duplicate the search scope instead of using versions?
I am using Sitecore SXA XM 10.2
| |
You cannot pass a parameter to Run() method but you can
set a property on your job class,
or pass constructor parameter, assign to a field and use it in your code.
See the UrlAgent class configuration:
<agent type="Sitecore.Tasks.UrlAgent" method="Run" interval="00:15:00">
<param desc="url">/sitecore/service/keepalive.aspx</param>
<LogActivity>true</LogActivity>
</agent>
and how it's used in the class:
public class UrlAgent
{
private readonly string _url;
private bool _logActivity = true;
public UrlAgent(string url)
{
this._url = url;
}
public bool LogActivity
{
get => this._logActivity;
set => this._logActivity = value;
}
public void Run()
{
string fullUrl = WebUtil.GetFullUrl(this._url);
if (this.LogActivity)
{
...
}
}
|
How to pass parameters in 'Run' method of the scheduling agent in Sitecore
I want to pass class object parameter to the Run method of the scheduling agent in the Sitecore.
Can I pass object parameter to the method and how?
How can I configure param in the config file?
Class:
public class ImportProduct
{
public void Run()
{
//Scheduling Agent calling
}
}
Config:
<scheduling>
<agent type="******.SchedulingAgent.ImportProduct" method="Run" interval="00:02:00">
</agent>
</scheduling>
| |
If you are using Experience Edge, you will need to store Sitemap in Media Item (This is recommended for XM Cloud version).
https://doc.sitecore.com/xmc/en/developers/xm-cloud/configure-a-sitemap.html
And make sure that you have media folder selected in Site Item's Sitemap media items field -
Hope this helps !!
|
Sitemap Graphql query returns blank data
I am trying to fetch Sitemap in my NextJs app using GraphQLSitemapXmlService plugin. This is XM Cloud and I am using Preview API locally.
During investigation, I realized that it is fetching response from following query which returns blank data (even in playground board). I have confirmed that other services are returning data like GraphQLRobotsService. What could be the problem?
(FYI, CM site also returns data with sitemap url)
query SitemapQuery($siteName: String!) {
site {
siteInfo(site: $siteName) {
sitemap
}
}
}
| |
I've seen such issues with the Sitecore form. If you are using a bundling/minification try with unbundled js once to get more information for syntax error if this occurs due to any custom js file.
Also if required js are not loading in a required order then possibly such error occurs.
Try out the below fixes
Make sure jquery.min.js file load only once on the page.
Check the order of the experience forms scripts.
Hope it helps!
|
Error occures while submiting sitecore forms
We have such console errors logged while submitting the Sitecore forms. We are using Sitecore 9.3.
We have used multi-page form and when submitting the form it submits the data but in the developer tool it shows such an error with thank you page.
VM2954:1 Uncaught TypeError: Cannot read properties of undefined (reading 'Constructor')
at <anonymous>:1:19
at b (jquery.min.js:2:839)
at Function.globalEval (jquery.min.js:2:2878)
at Object.dataFilter (jquery.min.js:2:80619)
at jquery.min.js:2:79084
at l (jquery.min.js:2:79486)
at XMLHttpRequest.<anonymous> (jquery.min.js:2:82254)
at Object.send (jquery.min.js:2:82613)
at Function.ajax (jquery.min.js:2:78223)
at Function.<anonymous> (jquery-migrate.js:378:22)
VM2567:3 Uncaught TypeError: Cannot read properties of undefined (reading 'parse')
at HTMLFormElement.eval (eval at a (jquery.unobtrusive-ajax.min.js:16:157), <anonymous>:3:25)
at Object.success (jquery.unobtrusive-ajax.min.js:16:1361)
at c (VM2387 jquery.min.js:2:28294)
at Object.fireWith [as resolveWith] (VM2387 jquery.min.js:2:29039)
at l (VM2387 jquery.min.js:2:79800)
at XMLHttpRequest.<anonymous> (VM2387 jquery.min.js:2:82254)
eval @ VM2567:3
success @ jquery.unobtrusive-ajax.min.js:16
| |
Add a processor to the renderField pipeline to perform a replacement of the default value of the setting with the value that applies to the context site.
Sitecore resolves the internal links in the Rich Text Editor by using the ExpandLinks processor in the renderField pipeline (located in the web.config file) converting the GUID into valid URLs, but letting the external links unhandled. So if you want to manipulate links, you could do it by adding a new processor into the renderField pipeline.
using System.Text.RegularExpressions;
using Sitecore.Data.Fields;
using Sitecore.Pipelines.RenderField;
namespace MySitecoreExtensions.Pipelines.RenderField
{
public class AddTargetAttributes
{
public void Process(RenderFieldArgs args)
{
if (args.FieldTypeKey == "rich text")
{
// custom logic to replace default value.
}
}
}
}
Patch config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<renderField>
<processor type="MySitecoreExtensions.Pipelines.RenderField.AddTargetAttributes, MySitecoreExtensions" patch:after="processor[@type='Sitecore.Pipelines.RenderField.GetInternalLinkFieldValue, Sitecore.Kernel']"/>
</renderField>
</sitecore>
</configuration>
References:
https://kirkegaard-at.blogspot.com/2015/10/sitecore-get-external-links-rte.html?m=0
https://sitecoretechfire.wordpress.com/2018/05/12/replace-external-links-and-internal-links-in-rich-text-field-dynamically/
Hope it helps!
|
How to customize "LinkItemNotFoundUrl" code?
We have a website running on Sitecore 10.2 and having multiple countries.
So in each country, if the particular link not found in rich text field, we need to redirect to particular country home page instead of /sitecore/service/notfound.aspx.
| |
Add "Encrypt": "Optional" to 4 occurrences of InvokeSqlcmd in xConnect-xp0.json file and run the installation.
Reference: http://navansitecorenotes.blogspot.com/2023/06/windows-11-pro-sitecore-101x.html
Hope it helps!
|
Sitecore 10.3 Installation failed due to SQL Server connection
I am trying to install Sitecore 10.3 instance on Windows 11. But I am getting the SSL error while xConnect is trying to connect to SQL Server. Error is
[ XConnectXP0_CreateShardApplication... : InvokeSqlcmd ------------------------]
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
[TIME] 00:04:25
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
| |
You should use separate security domains for each of the sites.
Instead of using
AuthenticationManager.BuildVirtualUser("extranet\\" + Email, true);
You should use for site1:
AuthenticationManager.BuildVirtualUser("site1\\" + Email, true);
and for site2:
AuthenticationManager.BuildVirtualUser("site2\\" + Email, true);
And then check if user is authenticated and belongs to the appropriate site domain.
|
How can create site specific virtual user for multi site implementation in Sitecore
Currently we are creating virtual user in Sitecore (9.0.2) database once user is authenticated with backend API as shown below
Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser("extranet\\" + Email, true);
We are checking the user is authenticated or not by using below code
((Sitecore.Security.Accounts.User)Sitecore.Context.User).IsAuthenticated
Now the problem is, we are adding one more website within same App service that will use same code. Only difference is that site1 and site2 have different virtual directory as shown below
Site1: www.site.come/site1
Site2: www.site.com/site2
We need to authenticate user against each site separately. Means one user can able to login site1 and site 2 from single browser.
Currently what is happening is that if a user logged into site 1 user is also logged into site 2. this should not happen.
Your help is most welcome.
| |
Sitecore has two session types: private and shared. If you CD server is scaled out to multiple instances and you don't use sticky session (ARR affinity cookie) then both session types should use an external session storage.
Here is an example for SQL session provider:
For private session modify your web.config file to use a custom provider:
<sessionState mode="Custom" customProvider="mssql" cookieless="false" timeout="20">
<providers>
<add name="mssql"
type="Sitecore.SessionProvider.Sql.SqlSessionStateProvider,
Sitecore.SessionProvider.Sql"
connectionStringName="sharedsession"
pollingInterval="2"
compression="true"
sessionType="private"/>
</providers>
</sessionState>
For shared session create a patch file for for the config Sitecore.Analytics.Tracking.Config and modify the section sitecore/tracking/sharedSessionState:
<sharedSessionState defaultProvider="mssql">
<providers>
<clear/>
<add name="mssql"
type="Sitecore.SessionProvider.Sql.SqlSessionStateProvider,Sitecore.SessionProvider.Sql"
connectionStringName="sharedsession"
pollingInterval="2"
compression="true"
sessionType="shared"/>
</providers>
</sharedSessionState>
Both session types can use the same connection string. The database is able to distinguish between different session types.
You can find more details about session storage and configuration examples for SQL and Redis providers in Sitecore documentation here.
|
Sitecore Abso Shared Session in XM scaled environment
I am trying to implement a website with shared session functionality with ARR affinity cookie disabled. The logged in user should be able to browse the website even though the request is served from a difference CD instance than the one user logged in. What is the best approach to store the user data and roles in session to implement this. We are using XM scaled architecture.
I have already updated the sessionType to Shared in my Sitecore instance but unfortunately I am not able to share the session data between servers.
<sessionState mode="Custom" customProvider="mssql" cookieless="false" timeout="20">
<providers>
<add name="mssql" type="Sitecore.SessionProvider.Sql.SqlSessionStateProvider, Sitecore.SessionProvider.Sql" connectionStringName="sharedSession"
pollingInterval="2" compression="true" sessionType="shared"/>
</providers>
</sessionState>
| |
Following steps allow to resume any EXM message manually:
Open your campaign in EXM.
Switch to Delivery tab
In the place where normally there is Send Campaign button, there will be now Resume button
|
Manually Resume paused EXM email campaigns
We have upgraded from Sitecore 9.3 to 10.3 after which the exm campaigns have moved to paused status.
How can i manually resume these campaigns?
I do not want an automated way of resuming the campaigns.
| |
XM Cloud support user membership, To create a user in XM Cloud, you must invite them to your Sitecore Cloud Portal organization and give them access to your XM Cloud app. When the team member logs in to the XM Cloud app, their user account is created in that XM Cloud app.
A team member must accept the invitation and log in to the XM Cloud app before an administrator can configure their access rights and security roles.
In the Sitecore Cloud Portal, you can assign the following app roles:
User - The XM Cloud user account has a content author role by default. You can assign security roles and access rights to their account.
Admin - A team member with an Admin role in the portal always has an administrator role in the XM Cloud app.
For more details refer below links.
https://doc.sitecore.com/xmc/en/developers/xm-cloud/creating-users-in-xm-cloud.html
https://doc.sitecore.com/portal/en/developers/sitecore-cloud-portal/invite-team-members-to-your-sitecore-cloud-portal-organization.html
https://doc.sitecore.com/xmc/en/developers/xm-cloud/add-a-user-to-a-role.html
Hope it helps!
|
Does Sitecore XM Cloud support user membership or other complex logic implementation?
It is known that XM cloud is based on a SaaS cloud platform. We are wondering if it supports user membership or similar functions.
If user membership is supported, could you please explain how it works and provide some tutorials or documentation?
If user membership is not currently supported, will it be a future release? Or would we need to integrate other products to achieve this functionality?
Please let me know if this captures your question properly. I'm happy to clarify or rephrase further.
| |
I generally recommend avoiding cloning at all costs (in almost all cases). That said, the role you need is sitecore\Sitecore Client Developing. This role is quite permissive and will also grant the user other developer/admin tier functionality.
Consider this lightweight solution instead:
We can define a custom role with a self documenting name, with the sole purpose of granting access to cloning functionality in the ribbon. Let's name the role Client Name && Item Cloning Ribbon && ALLOW READ. Then, update the permissions on the items:
Then, we assign that role to the user (or to another role) so we can easily see that they have those permissions via the "Member Of" role list.
Remember to also do the following (if applicable):
Serialize / back up the role
Serialize / back up the items in which the security permissions were changed on
Incorporate these updates in your identity provider claims configuration
|
Which permissions / roles are required for item cloning?
I have a user who needs the ability to clone items. The problem is that the clone options do not appear in the ribbon.
Expected State
Actual State
Which role do I need to assign the user to grant them the ability to clone?
| |
For someone who is having this issue, please follow the steps below to resolve it. XM Cloud local setup uses the preview to fetch the content from the master database. There seems to be an issue with images as they are requested form the web database. The issue will be fixed in later revisions. If you are facing this now, fix it by pointing Sitecore_ConnectionStrings_Web connection string to the master database locally. As web database is not used anymore for XM Cloud implementations, this shouldn't cause any harm. This connection string is defined in docker-compose.yml. You can change it in the file directly or override it in docker-compose-overrid.yml.
New value : Sitecore_ConnectionStrings_Web: Data Source=${SQL_SERVER};Initial Catalog=${SQL_DATABASE_PREFIX}.**Master**;User ID=${SQL_SA_LOGIN};Password=${SQL_SA_PASSWORD}
.Master is the change.
|
Fullstack local setup doesn't load images
After setting up the full stack locally, the rendering host is not able to load the newly added images. Network tab shows 404 for all those images.
| |
I have contacted to the Sitecore about the same. As per Sitecore response over support ticket:
We want to inform you that we are currently experiencing technical difficulties with our MyGet (https://sitecore.myget.org/ ) repository. As a result, there is an ongoing issue preventing the execution of both local and automated builds.
To address this situation, we recommend utilizing NuGet as an alternative during this period.
For comprehensive guidance on the workaround process, please refer to our knowledge article available at https://sitecore.service-now.com/kb?id=kb_article_view&sysparm_article=KB1002999.
We will keep you informed of any progress made through this page.
If there are further questions regarding this incident, please do not hesitate to raise a support case at the Sitecore Support & Self-Service Portal.
Transition of Sitecore public feeds from MyGet to NuGet after November 2023
Sitecore is moving its public feed from sitecore.myget.org to a different feed provider on November 30, 2023.
The URL of the new public feed is: https://nuget.sitecore.com/resources/v3/index.json
The URL for the internal artifact provider is: https://cloudsmith.io/~sitecore/repos/resources/groups/
The custom NPM feed will move from https://sitecore.myget.org/gallery/sc-npm-packages to the public NPM provider https://www.npmjs.com/
Both the original MyGet and the new public feeds are available now. After November 30, only the new NuGet and NPMJS public feeds will be available.
Sitecore strongly recommends that all customers and partners update their CI/CD processes and build scripts to use the new public feeds as soon as possible to avoid interruptions beyond November 30, 2023.
|
Sitecore MyGet repository access issue
Since two days sitecore.myget.org is down and we use https://sitecore.myget.org/F/sc-packages/ URL to restore the Sitecore packages from Nuget while deployment on server using CI/CD pipeline.
As sitecore.myget.org is down so build pipeline is failing, IS there any alternate approach/URL or when can expect it to up so that we can have our deployment on UAT/PROD environment.
| |
I have seen this happening when you have multiple site definitions. If you have multiple site definition items under Site Grouping, then I would suggest to keep only required one and mark rest others as non-publishable.
In your case,
You can mark CM definition item as unpublishable and then publish Site Grouping Node. (You can make sure that other definitions are removed from Web database.)
Clear cache and rebuild index as well.
If that works, please revert all your changes and see if that works again.
Though this sounds strange, I never got time to dig deep into its real cause.
I suspect this is due to the sequence these definition items are indexed in. I would recommend to keep one site definition per site.
|
Incorrect Canonical URL in Sitecore SXA Multisite - Domain Name gets appended twice
In our Sitecore 10.2 XM SXA website, the canonical URLs are not being generated properly - the domain name gets appended twice -
<link rel="canonical" href="https://prod.*******.orghttps://prod.*******.org/locations">
We have used OOTB Canonical URL rendering to add canonical URLs, added this rendering in our metadata partial.
Strangely, this issue occurs only in our PROD instance, it generates the correct URL in local and QA environments. Even shows the correct URL in PROD CM Experience Editor.
We have two Site Definition items in our Site Grouping - one for CM and the other for CD. I have compared the Site Definitions of all the instances, everything looks fine.
Unable to pin the cause or find a fix for this issue. Any help would be appreciated.
| |
There is no way to recover accidentally deleted data, categories or otherwise, on OrderCloud.
Source: I'm a lead developer of OrderCloud
|
Inputs needed on Restoring Categories in Sitecore Order Cloud
Issue:
We ran into an issue where the Sub Categories of the Category has been deleted in Sitecore Order Cloud due to which the Sub Categories and the Related products are not showing up on the Website.
Need inputs like is there is any way to restore the categories to a particular data so that we get the Sub Categories along with category.
Posting it as it needs an immediate fix.
Any Suggestions are Appreciated!
| |
You are in luck as Sitecore recently rushed out this page as most of the package are already migrated to the new provider (CloudSmith) planned for final go-live on the 30th November:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1002999
The URL of the new public feed is: https://nuget.sitecore.com/resources/v3/index.json
The URL for the internal artifact provider is: https://cloudsmith.io/~sitecore/repos/resources/groups/
The custom NPM feed will move from https://sitecore.myget.org/gallery/sc-npm-packages to the public NPM provider https://www.npmjs.com/
Thanks to Mark Cassidy for this info in Sitecore Slack.
|
Prolonged Unavailability of myorg: Seeking Alternative Sitecore Repositories
My team and I are currently engaged with a Sitecore Commerce project, and one of the key repositories we rely upon is https://sitecore.myget.org/F/sc-commerce-packages/api/v3/index.json. Regrettably, the myorg repository has been persistently and repeatedly offline, disrupting our work and causing concern among the team.
Given these circumstances, I am seeking advice on any other repositories that Sitecore SC might offer as potential alternatives to myorg.
I appreciate any guidance or suggestions you could provide.
Best Regards.
| |
Please see the following information from the KB article:
Sitecore is moving its public feed from sitecore.myget.org to a different feed provider on November 30, 2023.
The URL of the new public feed is: https://nuget.sitecore.com/resources/v3/index.json
The URL for the internal artifact provider is: https://cloudsmith.io/~sitecore/repos/resources/groups/
The custom NPM feed will move from https://sitecore.myget.org/gallery/sc-npm-packages to the public NPM provider https://www.npmjs.com/
Both the original MyGet and the new public feeds are available now. After November 30, only the new NuGet and NPMJS public feeds will be available.
Sitecore strongly recommends that all customers and partners update their CI/CD processes and build scripts to use the new public feeds as soon as possible to avoid interruptions beyond November 30, 2023.
Note: Sitecore Experience Commerce, Content Hub, Sitecore PowerShell and Sitecore Installation Framework packages are not yet available through the public feeds. We will update this article as soon as they are available.
Reference URL for latest updates: https://sitecore.service-now.com/kb?id=kb_article_view&sysparm_article=KB1002999
Rob Earlam created a blog post describing the ateps needed for updating an XM Cloud repo to the new feed: https://robearlam.com/blog/migrating-the-xm-cloud-introduction-repo-to-a-new-nuget-feed
|
Cannot access sitecore.myget.org
This has been asked a few times, it's a "current problem" that will not be of long term use on SSE, but because of the number of duplicate questions I'm creating this as a community wiki.
At the time of writing, myget.org is experiencing a major outage. The workaround is in the answer below:
| |
You can update the styling and functionality of any third party generated script.
Styling
Getting the generated HTML to resemble your sitecore website might be as simple as removing the link to the 3rd party CSS file. However this will totally depend on how the site and associated global css has been put together.
It's likely however that the generated html does not exactly match that which is expected, or the sitecore website forms HTML uses its own classes. If this is the case you will need to write additional selectors to deal with any discrepancies.
If the generated HTML has any inline scripts, you will need to counter these (with more css) to match your own style.
Scripting
Updating the functionality of the form to introduce additional client side validation will certainly be possible, but this will come with additional risk. You need to fully understand what the code is doing before making changes, as this could lead to the form failing in some way. This is often made more difficult because the 3rd party scripts are minified and/or obfuscated.
My suggestion would be to break down each task that you are trying to achieve and then ask a specific question related to that task. Each time including the all the details and source code that you have available, so as to better allow people to help
|
Integrate MS Dynamic CRM Form in Sitecore XP 9.3
What is the best approach to achieve below scenarios while integrating Dynamic CRM Form on a page in Sitecore XP 9.3?
Dynamic CRM Form should follow the same styles as Sitecore website. We already have few Sitecore Form implementation on few pages. Do we need to check CSS class applied on various Sitecore Form fields and apply the same CSS class in all fields in Dynamic CRM Form HTML OR we need to write separate CSS in Dynamic CRM Form itself to match the CSS with Sitecore website?
Client side input fields error handling. For example if all fields are blank, we need to show mandatory input field error message next to each fields and a div section just above the form which will have all error message as a bullet list. Do we need to write custom error handling JavaScript(jQuery) code in Sitecore JS file on page load OR Dynamic CRM Form can take care of this?
Please note in this case we're not using any MS Dynamic CRM module. It's just a form script generated by MS Dynamic CRM.
| |
Guys, I got the solution!!
I am writing it down below:
After adding this GRAPH_QL_ENDPOINT=/sitecore/api/graph/edge to the .env file, the error occurred.
Cause: I provided only path as the endpoint, you need to give the whole endpoint with site URL and path included. And if you check in src/temp/config.js you can see all the configurations for the project.
This was just some silly mistake, but learnt something new .
|
Invalid graphql endpoint, Verify that 'layoutServiceHost' property in 'scjssconfig.json' file or appropriate environment variable is set
I am a newbie here. I was editing the .env file for adding the graphQLEndpoints. But in between something broke and I got this error.
This is the scjssconfig.json file
{
"sitecore": {
"instancePath": "C:\\inetpub\\wwwroot\\rengokusc.dev.local",
"apiKey": "ED741CD3-65AB-495F-9510-************",
"deploySecret": "c2431oi1tk5a4k2cg5usr7jfxgtpqew396********",
"deployUrl": "https://rengokusc.dev.local/sitecore/api/jss/import",
"layoutServiceHost": "https://rengokusc.dev.local/"
}
}
I am using NextJS, Sitecore 10.3 (SXA with headless).
| |
title_t is a text_general field in Solr. Which is tokenized field so sorting will not work. If you want sorting then the field needs to be of string type (with _s suffix)
You can try a few things-
Create a computed index field that is of string type and apply sort on that.
Convert the title field from text to string via Sitecore patch config and apply sort
Create a copyField in Solr from text to string and then apply sort order on the string field.
|
Sort by title asc on Solr not working as expected
When trying sort search results in Solr using title (alphabetical) asc or desc does not work as expected and not sorted.
| |
Take a look View option in the menu, and ensure both Hidden Items and Entire Tree are checked.
Hope it helps!
|
Template item not displaying role based user - 10.2
I created the new user and assigned designer, author, and content authoring roles to the newly created user. Whenever I logged in as a new user some of the template items is not visible in the content tree. I have given read access for all the templates but those are not visible in the under-home item. for example, under templates/foundation/local data source/page data this template is not visible in under any item.
| |
If that works on local and not on Vercel, then I suspect its related to configuration (as you said). Here are details of how its implementation uses configuration and you can check those.
With SXA setup, you get a sitemap-fetcher plugin. It resides at path - src\rendering\src\lib\sitemap-fetcher\plugins\graphql-sitemap-service.ts
If you check its constructor -
constructor() {
this._graphqlSitemapService = new GraphQLSitemapService({
endpoint: config.graphQLEndpoint,
apiKey: config.sitecoreApiKey,
siteName: config.jssAppName,
});
Assuming you are using GraphQl endpoint, you will need to share AppName if you have multisite setup in environment variables.
Second thing to look at is it's implementation,
async exec(context?: GetStaticPathsContext): Promise<StaticPath[]> {
if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
return [];
}
return process.env.EXPORT_MODE
? this._graphqlSitemapService.fetchExportSitemap(config.defaultLanguage)
: this._graphqlSitemapService.fetchSSGSitemap(context?.locales || []);
}
If you have multilingual setup, you can check your default language (in config.json).
If this is all well then you can check if GraphQl query returns Sitemap.
EDIT 1 -
If you are using Experience Edge, you will need to store Sitemap in Media Item (This is recommended for Cloud version but no harm in trying).
https://doc.sitecore.com/xmc/en/developers/xm-cloud/configure-a-sitemap.html
And make sure that you have media folder selected in Site Item's Sitemap media items field -
|
Sitemap.XML for Sitecore JSS NextJS using SXA
We are working on 10.2 Sitecore JSS (NextJS) using SXA. We have enabled Sitemap.xml in Sitecore using OOTB SXA settings. We can see sitemap item at this path /sitecore/content/TenantName/Home/Settings/Sitemap
The
sitemap.xml URL is working fine for the Sitecore domain (CM server), we can see all the desired URLs.
Our NextJS application is hosted on Vercel, but when we check the sitemap.xml URL in the Vercel domain, it gives a 404 error.
Does any specific thing need to be enabled to make sitemap.xml work for NextJS application hosted on Vercel?
Update:
We are fetching layout data with the JSS REST Layout Service.
Sitemap.xml is not working on localhost:3000 as well.
| |
A custom content rendering resolver is one option. But also, if you are using Next.js you can always use the useSitecoreContext hook and access the context item fields from that object. This will save you writing custom code.
For an example you can look at the Headless SXA Page Content component. This will use a datasource item if provided, otherwise it will use the context item:
const { sitecoreContext } = useSitecoreContext();
const field = (props.fields && props.fields.Content
? props.fields.Content
: sitecoreContext?.route?.fields?.Content) as RichTextField;
Ref: https://github.com/Sitecore/jss/blob/7d2b47bf9495b4301ecc07f5f62f852fb2e34f87/packages/create-sitecore-jss/src/templates/nextjs-sxa/src/components/PageContent.tsx#L35C21-L35C21
|
Sitecore rendering contents resolver - need content from both context item and datasource item
We are working on Sitecore 10.3 Headless.
For one of the components we are developing, we need the title field from the context item and rest of the content from Datasource item.
In this case if we select Context Item Resolver then we miss content from Datasource item and if we select Datasource Resolver then we miss content from context item.
Do we need to create a Custom Item resolver which has content from context item and also from Datasource item ?
| |
The Fix
To make sure that the content delivery api token is not exposed to the browser, you need to remove the following line from the ./scripts/generate-config.js:
/*
CONFIG GENERATION
Generates the /src/temp/config.js file which contains runtime configuration
that the app can import and use.
*/
const defaultConfig: JssConfig = {
****
sitecoreApiKey: process.env[`${constantCase('sitecoreApiKey')}`], <---- REMOVE THIS LINE!!!!!
****
sitecoreApiHost: process.env[`${constantCase('sitecoreApiHost')}`],
jssAppName: process.env[`${constantCase('jssAppName')}`],
graphQLEndpointPath: process.env[`${constantCase('graphQLEndpointPath')}`],
defaultLanguage: process.env[`${constantCase('defaultLanguage')}`],
graphQLEndpoint: process.env[`${constantCase('graphQLEndpoint')}`],
layoutServiceConfigurationName: process.env[`${constantCase('layoutServiceConfigurationName')}`],
};
This will make sure that the API token is only ever pulled from the server side environment variables.
How do I make GraphQL calls from the browser now?
Once this change is made, you can't make graphql calls directly to Experience Edge as the content token is not known. To do this, you can create an API in route in your Next.js application that will make the call out to Experience Edge and return the results to the browser:
... the above us pseudo code and would need to be completed properly. But this now hides away the call to Experience Edge behind an api route in your Next.js app.
|
How can I secure the Experience Edge content delivery token on my Next.js/JSS app?
I am using Sitecore Experience Edge and Next.js with JSS. My site requires a section that is secured behind a login, which I know should be handled by the head application and that we should not expose the Edge content delivery token to the browser to make sure that the content cannot be accessed directly.
The problem is, JSS generates a file under ./temp/config.ts that contains the token:
config.sitecoreApiKey = process.env.SITECORE_API_KEY || '<api token will be added here>',
This file is imported into some components and so this exposes the API token to the world. Can we configure JSS to stop exposing that token?
| |
Sitecore CLI 4.2.1 does in fact depend on .NET Core 3.1.
.NET Core 3.1 reached end of life at the end of 2022:
https://devblogs.microsoft.com/dotnet/net-core-3-1-will-reach-end-of-support-on-december-13-2022/
It does appear as though the windows-latest build agent no longer ships with 3.1. You may be able to install 3.1 on the build agent as part of your build pipeline, but it would probably be a better idea to update the Sitecore CLI version. See the CLI download page here:
https://dev.sitecore.net/Downloads/Sitecore_CLI.aspx
You will also need to update your version of Sitecore Management Services on your CM instance(s).
Here are the necessary modifications to fix your build pipeline:
script: |
dotnet new tool-manifest
dotnet tool install Sitecore.CLI --ignore-failed-sources --version 5.2.113
dotnet sitecore plugin add -n Sitecore.DevEx.Extensibility.Serialization --version 5.2.113
dotnet sitecore ser pkg create -o "acme_content.itempackage"
Make sure to update any README files / documentation. This should be updated on your local development environment(s) as well. Running the above commands locally will result in some changes to the files dotnet-tools.json and sitecore.json.
|
DevOps build pipeline failing on SCS serialize/package step
My DevOps builds recently started failing on the step in which we use the Sitecore CLI and SCS to build an item package. To my knowledge, nothing has changed on our end, so it is unclear why the build consistently fails. We are using Sitecore CLI v 4.2.1, which apparently depends on .NET Core v 3.1.0.
Below is the relevant portion of my build pipeline:
pool:
vmImage: 'windows-latest'
demands:
- msbuild
- visualstudio
steps:
- task: PowerShell@2
displayName: Build Sitecore Items Package
inputs:
targetType: 'inline'
script: |
dotnet new tool-manifest
dotnet tool install Sitecore.CLI --ignore-failed-sources --version 4.2.1
dotnet sitecore plugin add -n Sitecore.DevEx.Extensibility.Serialization --version 4.2.1
dotnet sitecore ser pkg create -o "acme_content.itempackage"
Here is the build log and error:
2023-07-28T15:33:59.0709582Z ##[section]Starting: Build Sitecore Items Package
2023-07-28T15:33:59.0820727Z ==============================================================================
2023-07-28T15:33:59.0820850Z Task : PowerShell
2023-07-28T15:33:59.0820909Z Description : Run a PowerShell script on Linux, macOS, or Windows
2023-07-28T15:33:59.0820983Z Version : 2.220.0
2023-07-28T15:33:59.0821035Z Author : Microsoft Corporation
2023-07-28T15:33:59.0821117Z Help : https://docs.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
2023-07-28T15:33:59.0821201Z ==============================================================================
2023-07-28T15:33:59.9871431Z Generating script.
2023-07-28T15:34:00.0366626Z ========================== Starting Command Output ===========================
2023-07-28T15:34:00.0599141Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\35ce6ca2-f837-4d3d-844a-373eaf773575.ps1'"
2023-07-28T15:34:19.1818561Z Creating this template will make changes to existing files:
2023-07-28T15:34:19.1831407Z Overwrite ./.config/dotnet-tools.json
2023-07-28T15:34:19.1831579Z
2023-07-28T15:34:19.1831953Z Rerun the command and pass --force to accept and create.
2023-07-28T15:34:19.1857491Z
2023-07-28T15:34:32.9432568Z You can invoke the tool from this directory using the following commands: 'dotnet tool run sitecore' or 'dotnet sitecore'.
2023-07-28T15:34:32.9433241Z Tool 'sitecore.cli' (version '4.2.1') was successfully installed. Entry is added to the manifest file D:\a\1\s\.config\dotnet-tools.json.
2023-07-28T15:34:33.3864634Z You must install or update .NET to run this application.
2023-07-28T15:34:33.3864948Z
2023-07-28T15:34:33.3865560Z App: C:\Users\VssAdministrator\.nuget\packages\sitecore.cli\4.2.1\tools\netcoreapp3.1\any\sitecore.cli.dll
2023-07-28T15:34:33.3865913Z Architecture: x64
2023-07-28T15:34:33.3868213Z Framework: 'Microsoft.NETCore.App', version '3.1.0' (x64)
2023-07-28T15:34:33.3868780Z .NET location: C:\Program Files\dotnet\
2023-07-28T15:34:33.3868981Z
2023-07-28T15:34:33.3869340Z The following frameworks were found:
2023-07-28T15:34:33.3870358Z 6.0.5 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
2023-07-28T15:34:33.3871934Z 6.0.20 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
2023-07-28T15:34:33.3872142Z
2023-07-28T15:34:33.3872596Z Learn about framework resolution:
2023-07-28T15:34:33.3873373Z https://aka.ms/dotnet/app-launch-failed
2023-07-28T15:34:33.3873603Z
2023-07-28T15:34:33.3874024Z To install missing framework, download:
2023-07-28T15:34:33.3876559Z https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=3.1.0&arch=x64&rid=win10-x64
2023-07-28T15:34:33.5787559Z You must install or update .NET to run this application.
2023-07-28T15:34:33.5788698Z
2023-07-28T15:34:33.5796898Z App: C:\Users\VssAdministrator\.nuget\packages\sitecore.cli\4.2.1\tools\netcoreapp3.1\any\sitecore.cli.dll
2023-07-28T15:34:33.5800203Z Architecture: x64
2023-07-28T15:34:33.5809111Z Framework: 'Microsoft.NETCore.App', version '3.1.0' (x64)
2023-07-28T15:34:33.5813020Z .NET location: C:\Program Files\dotnet\
2023-07-28T15:34:33.5815235Z
2023-07-28T15:34:33.5816388Z The following frameworks were found:
2023-07-28T15:34:33.5825653Z 6.0.5 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
2023-07-28T15:34:33.5837279Z 6.0.20 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
2023-07-28T15:34:33.5837783Z
2023-07-28T15:34:33.5840580Z Learn about framework resolution:
2023-07-28T15:34:33.5842273Z https://aka.ms/dotnet/app-launch-failed
2023-07-28T15:34:33.5843214Z
2023-07-28T15:34:33.5850337Z To install missing framework, download:
2023-07-28T15:34:33.5877002Z https://aka.ms/dotnet-core-applaunch?framework=Microsoft.NETCore.App&framework_version=3.1.0&arch=x64&rid=win10-x64
2023-07-28T15:34:33.8507014Z ##[error]PowerShell exited with code '1'.
2023-07-28T15:34:33.8864408Z ##[section]Finishing: Build Sitecore Items Package
My guess is that because we are using the windows-latest build agent, something changed and .NET Core 3.1 is no longer included by default. I also tried changing the build agent to windows-2022 and even windows-2019 (the oldest option) and it only went as far back as .NET Core version 6.x.
| |
Having recently implemented something similar (I wrote about it here), I think you may be missing a config that essentially whitelists the conditions that can be used on the cortex processing role. NB: The service will depend on your topology. It is the service that accepts the tasks (eg. xconnect in xp0, cortexprocessing in xp1).
You'll need to add a patch similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<Sitecore>
<Processing>
<Services>
<DataPurgeTaskOptionsValidatorOptions>
<Options>
<AllowedContactConditionIds>
<AintNoInteractions>ContactNoInteractionsCondition</AintNoInteractions>
</AllowedContactConditionIds>
</Options>
</DataPurgeTaskOptionsValidatorOptions>
</Services>
</Processing>
</Sitecore>
</Settings>
Not sure why, but it's not mentioned in the walkthrough, but will result in the behavour you're seeing if it's not there. For reference, the base config can be found in App_Data/Config/Sitecore/Processing/sc.XConnect.DataPurge.Validation.xml .
Bonus:
Unfortunately some bad news, as I think what you're trying to achieve won't work without some additional work as the Contact object passing through in IsAccepted won't have any Interactions in the property. You could verify this with some debugging/additional logging to test. You would need to find a way to query this data via usual methods (e.g. xconnect or search client). This is explicity called out in a note in the documentation:
The conditions are limited to filter by contact data and contact
identifiers. You cannot create a condition based on the contact facet
or interaction data in Sitecore 10.1.
NB: that's from the 10.2 walkthrough doco you referred to.
|
XConnect and CLI not acknowledging a custom purge condition
I'm trying to create an XConnect custom contact purge condition for any contacts with 0 interactions. I've followed this walkthrough but I must be missing something as it's not registered when trying to run it via the CLI.
This is the walkthrough I'm using.
Implemented an ICondition interface
using Sitecore.XConnect;
using Sitecore.XConnect.DataTools.Abstractions.Conditions;
namespace PlanetExpress.Foundation.Models.Conditions
{
public class ContactNoInteractionsCondition : ICondition
{
public string ConditionId { get; } = "ContactNoInteractionsCondition";
public bool IsAccepted(Contact contact)
{
return contact.Interactions.Count == 0;
}
}
}
The reason why it's PlanetExpress.Foundation.Models is because it'll be copied across to XConnect with the way we deploy our containers along with other custom facets. I've checked the XConnect container and can see the DLL is there.
Register the custom condition
Created the config - as it will process the patch after the config under Processing
App_Data/Config/Sitecore/Processing_patch/sc.XConnect.DataTools.Conditions.xml
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<Sitecore>
<Processing>
<Services>
<Condition.AnonymousCondition>
<Type>Sitecore.XConnect.DataTools.Conditions.AnonymousCondition, Sitecore.XConnect.DataTools.Conditions</Type>
<As>Sitecore.XConnect.DataTools.Abstractions.Conditions.ICondition, Sitecore.XConnect.DataTools.Abstractions</As>
<LifeTime>Singleton</LifeTime>
</Condition.AnonymousCondition>
<Condition.ContactNoInteractionsCondition>
<Type>PlanetExpress.Foundation.Models.Conditions.ContactNoInteractionsCondition,PlanetExpress.Foundation.Models</Type>
<As>Sitecore.XConnect.DataTools.Abstractions.Conditions.ICondition, Sitecore.XConnect.DataTools.Abstractions</As>
<LifeTime>Singleton</LifeTime>
</Condition.ContactNoInteractionsCondition>
</Services>
</Processing>
</Sitecore>
</Settings>
There is another config file in the same folder, and that config does apply (to adjust cutoffdays). I can see the conditions config file sitting on the container as well, so it exists.
I'm not sure if the code will do the job, trying to test it, however, the issue I'm having is that ContactNoInteractionsCondition doesn't get picked up by XConnect\CLI when running the following command
$ dotnet sitecore xconnect purge contacts start --cds "ContactNoInteractionsCondition" --cutoffdays 91 -t -v
Registering delete contacts task: cutoffDays = 91;conditions = ContactNoInteractionsCondition;batchSize = 100;
Cannot register delete contacts task. The following conditions are not found: ContactNoInteractionsCondition
An error has occurred, and the task is not registered.
Sitecore instance is 10.2
CLI is running [email protected] version of the plugin
| |
You can refer to this article to create a reCAPTCHA 3 with your Sitecore form.
https://dev.to/chandra_kodi/sitecore-google-recaptcha-v3-5d18
Here are the steps you can use to create the reCAPTCHA 3.
Create a new model class - GoogleRecaptchaV3.cs
public class GoogleRecaptchaV3 : StringInputViewModel
{
public string ApiKey { get; set; }
public string ErrorMessage { get; set; }
protected override void InitItemProperties(Item item)
{
base.InitItemProperties(item);
ApiKey = Sitecore.StringUtil.GetString(item.Fields["Api Key"]);
ErrorMessage = Sitecore.StringUtil.GetString(item.Fields["Error Message"]);
}
protected override void UpdateItemFields(Item item)
{
base.UpdateItemFields(item);
item.Fields["Api Key"].SetValue(ApiKey, true);
item.Fields["Error Message"].SetValue(ErrorMessage, true);
}
}
Create custom validation class - CaptchaV3Validator.cs
public class CaptchaV3Validator : ValidationElement<string>
{
public override IEnumerable<ModelClientValidationRule> ClientValidationRules
{
get
{
if (string.IsNullOrEmpty(this.ApiKey))
{
yield break;
}
}
}
protected virtual string ApiKey { get; set; }
protected virtual string Title { get; set; }
protected virtual string FieldName { get; set; }
public CaptchaV3Validator(ValidationDataModel validationItem) : base(validationItem)
{
}
public override void Initialize(object validationModel)
{
base.Initialize(validationModel);
StringInputViewModel stringInputViewModel = validationModel as StringInputViewModel;
if (stringInputViewModel != null)
{
var fieldItem = Sitecore.Context.Database.GetItem(ID.Parse(stringInputViewModel.ItemId));
if (fieldItem != null)
{
this.ApiKey = fieldItem["Api Key"];
}
this.Title = stringInputViewModel.Title;
this.FieldName = stringInputViewModel.Name;
}
}
public override ValidationResult Validate(object value)
{
if (value == null)
{
return new ValidationResult("Captcha is Inavlid.");// ValidationResult.Success;
}
var isCaptchaValid = ValidateCaptcha((string)value, this.ApiKey);
if (!isCaptchaValid)
{
return new ValidationResult(this.FormatMessage(new object[] { this.Title }));
}
return ValidationResult.Success;
}
public static bool ValidateCaptcha(string response, string secret)
{
HttpClient httpClient = new HttpClient();
var res = httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret=" + secret + "&response=" + response + "").Result;
if (res.StatusCode != HttpStatusCode.OK)
return false;
string JSONres = res.Content.ReadAsStringAsync().Result;
dynamic JSONdata = JObject.Parse(JSONres);
if (JSONdata.success != "true")
return false;
return true;
}
}
Create a View at location Views/FormBuilder/FieldTemplates- GoogleRecaptchaV3.cshtml
@using Sitecore.ExperienceForms.Mvc.Html
@model Glass.Mapper.Training.FormFields.GoogleRecaptchaV3
<input id="@Html.IdFor(m => Model.Value)" name="@Html.NameFor(m => Model.Value)" class="@Model.CssClass" type="hidden" value="" />
<script src="https://www.google.com/recaptcha/api.js?onload=grecaptcha_ready&[email protected]"></script>
<script>
function grecaptcha_ready() {
grecaptcha.ready(function () {
grecaptcha.execute('@Model.ApiKey', { action: 'form' }).then(function (token) {
document.getElementById("@Html.IdFor(m => Model.Value)").value = token;
});
});
}
var hiddenField = document.getElementById(@Html.Raw("\"" + Html.IdFor(m => Model.Value) + "\""));
var parent = hiddenField.parentNode;
if (parent.classList.contains("sc-formdesign-fieldcontainer")) {
var textDiv = document.createElement("div");
textDiv.innerHTML = "(ReCaptcha V3 Hidden Field)";
parent.appendChild(textDiv);
}
CORE db
Create a form property by copying one of existing items ”SingleLineText” and rename the copied item as “GoogleReCaptchaV3”. /sitecore/client/Applications/FormsBuilder/Components/Layouts/PropertyGridForm/PageSettings/Settings/GoogleReCaptchaV3
MASTER db
In the Sitecore Content Editor, navigate to /sitecore/templates/System/Forms/Fields.
Then add new template with name “CustomRecaptchaV3” and select Base template /sitecore/templates/System/Templates/Template
This template must inherit as below
Create new Validation item at /sitecore/system/Settings/Forms/Validations as CaptchaV3 Validation.
Create new Field type at /sitecore/system/Settings/Forms/Field Types/Security with name Google Recaptcha V3.
Now we are ready to use ReCaptcha V3 in Forms. Go to Sitecore Forms and simply drag and drop Google ReCaptcha V3 field under Security.
Hope this will help.
|
How to include reCAPTCHA(version 3) in Sitecore Form 9.3.0?
How to include reCAPTCHA(version 3) in Sitecore Form 9.3.0 ?
| |
Yes, it is expected. In the Content Editor and the Experience Editor, you can restrict the publication of items using publishing restrictions. Publishing restrictions let you specify that a specific item or a version of an item is publishable or unpublishable, either within a specific date range or indefinitely. In this way, you can control which items and pages are available for publishing at any given time.
If you clear the Publishable check box, this affects all the item versions listed on the Versions tab. This means that if you specify an item as not publishable, you cannot make a version of that item publishable. When you publish, the item and all its versions are removed from the target database.
Below are the ways to handle it.
Delete the Location item using Breaking Link's dialog with the appropriate action.
Remove Links
Link to another item.
Provide the content author with such an ability so it could be prevented in the future using Powershell or custom development.
References:
https://thesitecorist.net/2019/08/17/un-publish-buttons-using-spe/
https://www.skillcore.net/sitecore/sitecore-unpublish-and-delete-item
Hope it helps!
|
Remove link of item marked as Unpublishable
I have 2 templates, Location and Provider. Provider has Locations associated in a Multilist field.
At times, I need to mark the Location non-publishable. But when I do this and publish it (ultimately deleting non-publishable Location item from WEB), Provider's Location field shows a broken link.
This causes problem while indexing data as it indexes broken links as well.
But is this really expected? This seems Sitecore's default behavior. Shouldn't it be cleared automatically?
Note: I tried rebuilding the link database but that did not clear that
broken link.
| |
All your properties must be virtual, e.g.
[SitecoreField(FieldId = "{63A954E5-5A8F-46DE-B361-7C2CEB908F8A}")]
public virtual Image Logo { get; set; }
Why? Glass mapper generates a proxy class of your class dynamically. In order to make sure that proxy class can override the property, it has to be marked as virtual.
See Glass Mapper documentation examples:
https://training.glass.lu/courses/367234/lectures/5610541
Also notice that all the properties on a class use the virtual keyword. This is required. If you don't mark your properties as virtual, Glass.Mapper can't lazy load data.
|
GlassMapper 5 is returning null properties
I'm trying to get items from Sitecore using GlassMapper 5 and after trying in many ways the properties in my object are always null.
Here are my templates.
And this is my content tree structure
The MainNav item is being used as datasource of a rendering and this how I'm getting it in the controller.
public ActionResult NavigationHeader()
{
var ds = MvcContext.GetDataSourceItem<MainNav>();
if (ds == null)
{
return null;
}
return View("~/Views/Redesign/Navigation/NavigationHeader.cshtml", ds);
}
I've tried to disable lazy loading
var ds = MvcContext.GetDataSourceItem<MainNav>(new GetKnownOptions { Lazy = Glass.Mapper.LazyLoading.Disabled })
But by doing that an exception is thrown
Model depth check failed. Model graph too large, enable lazy loading.
Here is how my MainNav class is defined
[SitecoreType(TemplateId = "{93110014-14DC-4380-B031-54A31358AD9E}")]
public class MainNav : GlassMapperBase
{
[SitecoreField(FieldId = "{63A954E5-5A8F-46DE-B361-7C2CEB908F8A}")]
public Image Logo { get; set; }
[SitecoreChildren]
public IEnumerable<INavigation> Navigation { get; set; }
}
I've already tried to enable AutoMap and EnforceTemplate.
I've already checked the Template Id as well as the Field Id and they are correct.
I've already removed the SitecoreType annotation from MainNav class.
I've already checked the MainNav Item versions and there is only one.
I've already checked the web database and everything is exactly like in the master.
I've already checked the language and both, the site definition and the
Sitecore.Context.Language are defined as "en".
In the view, when I try to access Model.Logo or Model.Navigation, those properties are always null but in the immediate window, I can access TemplateId or Name properties defined in GlassMapperBase class.
I really don't know what else to try.
| |
It's all described in Sitecore documentation here:
https://doc.sitecore.com/xp/en/developers/103/platform-administration-and-architecture/add-custom-fields-to-a-solr-schema.html
In shortcut:
You need to create your own ISchemaPopulateHelper implementation, best by overriding SchemaPopulateHelper, e.g.
public class CustomPopulateHelper : SchemaPopulateHelper
{
public CustomPopulateHelper(SolrSchema schema) : base(schema)
{
}
...
}
And your own factory like:
public class CustomPopulateHelperFactory : IPopulateHelperFactory
{
public ISchemaPopulateHelper GetPopulateHelper(SolrSchema solrSchema)
{
return new CustomPopulateHelper(solrSchema);
}
}
Then register the factory in patch file:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<contentSearch.PopulateSolrSchema>
<processor type="Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.PopulateFields, Sitecore.ContentSearch.SolrProvider">
<param type="Documentation.Examples.CustomPopulateHelperFactory, Documentation.Examples" patch:instead="*[@type='Sitecore.ContentSearch.SolrProvider.Factories.DefaultPopulateHelperFactory']"/>
</processor>
</contentSearch.PopulateSolrSchema>
</pipelines>
</sitecore>
</configuration>
|
What is the way to update solr schema using code in sitecore 10.3?
I need to update Solr schema for text highlighting using code.
What is the way to update Solr schema using code in Sitecore 10.3?
Since 'SolrProvider.GetHelper is obsolete'
| |
Navigating in Content Editor is not really what Sitecore Powershell Extension is built for. But it's possible to run javascript from SPE that will do the redirect for you:
$id = $deletedItem.Parent.ID.ToString()
$script = ('window.top.location = "/sitecore/shell/Applications/Content%20Editor?fo=' + $id +'"')
Invoke-JavaScript -Script $script
Be aware that if you add this at the end of your SPE script, it will not show message saying that script execution is completed and will redirect immediately to the parent item.
|
How to switch to another item from context item using SPE?
I have an SPE script which content team runs from the script context menu. The script deletes the current context item. Once the item is deleted, and I close the script pop-up. I get another pop-up saying the selected item could not be found.
Is there a way to select another item (parent item in my case) in the tree node after the item is deleted so that this warning message can be avoided.
Also, is there a way to refresh the content tree from the selected node from SPE?
| |
There are a couple of things you could try and eliminate first..
File locking: Do you have a virus checker that could be locking the files and stopping them from being overwritten or possibly deleting them? Do you have drive sharing that could cause issues like this.
Permissions: Do the Data and indexes folders have the correct permissions i.e. does the user the IIS worker process is running under (e.g. NETWORK SERVICE) have write and delete access to these folders.
Configuration: Check that nothing has changed any of the Lucene index definitions in the Sitecore section of the web.config.
Rebuilding the index via the control panel or go into the Data\indexes\sitecore_web_index directory and delete everything in there before you do the rebuild just in case anything has corrupted something in the existing index. Depending on how many items you have the index shouldn't take very long at all, so if it hangs like that it normally indicates a problem.
Hope it helps!
|
Lucene Index- Sitecore Web index _sat0.cfs file is missing
We are using Lucene index in Sitecore environment. We are facing file not found issue recently in the web page. master index is working fine but in master index there is no file related to this name.
Server Error in '/' Application.
Could not find file 'C:\inetpub\wwwroot\website\Data\indexes\sitecore_web_index\_sat0.cfs'.
Description: An unhandled exception occurred.
Exception Details: System.IO.FileNotFoundException: Could not find file 'C:\inetpub\wwwroot\website\Data\indexes\sitecore_web_index\_sat0.cfs'.
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:
[FileNotFoundException: Could not find file 'C:\inetpub\wwwroot\website\Data\indexes\sitecore_web_index\_sat0.cfs'.]
Lucene.Net.Index.FindSegmentsFile.Run(IndexCommit commit) in d:\Lucene.Net\FullRepo\trunk\src\core\Index\SegmentInfos.cs:736
Lucene.Net.Index.DirectoryReader.Open(Directory directory, IndexDeletionPolicy deletionPolicy, IndexCommit commit, Boolean readOnly, Int32 termInfosIndexDivisor) in d:\Lucene.Net\FullRepo\trunk\src\core\Index\DirectoryReader.cs:117
Sitecore.ContentSearch.LuceneProvider.Sharding.LuceneShard.<CreateReader>b__11_0(LuceneIndexAccess access) +73
Sitecore.ContentSearch.LuceneProvider.Sharding.LuceneShard.CreateReader(LuceneIndexAccess indexAccess) +161
Sitecore.ContentSearch.LuceneProvider.Sharding.LuceneShard.CreateSearcher(LuceneIndexAccess indexAccess) +52
System.Linq.WhereSelectArrayIterator`2.MoveNext() +78
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +158
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +93
Sitecore.ContentSearch.LuceneProvider.LuceneSearchContext.Initialize(ILuceneProviderIndex index, ILuceneProviderSearchable[] searchables, LuceneIndexAccess indexAccess) +173
Sitecore.ContentSearch.LuceneProvider.LuceneIndex.CreateSearchContext(SearchSecurityOptions securityOptions) +110
| |
If you are on XP and have xDB and xDB tracking enabled, then you can enable robot detection on your your forms. But, this will not protect against replay attacks.
The robot detection will filter out unwanted interactions from bots and ensure that only genuine contacts are registered in xDB.
If you want to have similar protection levels on your forms that a recaptcha provides, then you will need to add a recaptcha.
references:
https://doc.sitecore.com/xp/en/users/103/sitecore-experience-platform/work-with-robot-detection-for-forms.html
https://doc.sitecore.com/xp/en/developers/103/sitecore-experience-platform/robot-detection-overview.html
|
Is Recaptcha really needed to prevent bots attack in your Sitecore forms SXA 9.3?
Is Recaptcha really needed to prevent bots attack in your Sitecore forms SXA 9.3? My need is I want to prevent bot attack in my website. I have a sitecore form which is capturing user email. Do I really need Recaptcha or Sitecore handles it internally?
| |
Triggering Webhooks when publishing content: when prerendering the application with static generation or deploying static HTML with next export, you must trigger a next build and site deployment on publishing new content. To facilitate this, Sitecore Headless Services and Sitecore Experience Edge for XM can invoke a webhooks. You can leverage Sitecore webhooks with Vercel deploy hooks.
This documentation is misleading. It very much depends on how you are hosting your application:
Pure Static Hosting:
If you are hosting your site entirely statically, on a CDN for example, and you are deploying your site using next export, then yes, for a content change to be visible on your site, you must re-export your next application using next export again. Whether you do this on every content change or have a scheduled approach, say every 2 hours we redeploy, that is up to the project's requirements.
Hybrid Hosting (Vercel, Netlify, ASWA Hybrid Mode etc...)
If you are hosting on a more recommended approach, like Vercel, that do a hybrid host - a combination of statically generated pages plus the addition of middleware, serverless functions and regeneration, you do not need to redeploy your app to see content changes. You can use ISR (Incremental Static Regeneration) or On Demand Revalidation in you application to see the updated content. Both of these are a better option than re-deploying the application.
There are considerations for both tho. With ISR you will need to tune your revalidation period to find a balance between using up all your serverless function executions and how quick the client wants content to be visible on the site after a publish.
On Demand Revalidation can take care of that, but you will need to implement the revalidation functions called by the Experience Edge web hooks and make sure that you don't overload your executions that way.
Its all a balancing act based on how fast you want everything vs how much you want to pay for that speed.
|
Excessive next builds and deploys (triggered by publish webhooks) for SSG
The Sitecore docs on deploying JSS Next.JS sites to Vercel state that you must trigger a next build and site deployment via webhook on publish in order to pre-render the site with static site generation (SSG):
Triggering Webhooks when publishing content:
when prerendering the
application with static generation or deploying static HTML with next
export, you must trigger a next build and site deployment on
publishing new content. To facilitate this, Sitecore Headless Services
and Sitecore Experience Edge for XM can invoke a webhooks. You can
leverage Sitecore webhooks with Vercel deploy hooks.
It seems excessive to constantly be running builds and deployments whenever content is published. It creates noise and can result in excess serverless function executions (SFE). Vercel recommends incremental static generation (ISR) and on demand revalidation, instead of full builds for webhook events which are constantly happening.
Another docs page seems to indicate that the static pages can be updated after having already built, so there doesn't appear to be any limitations about how to configure the site:
When statically generating JSS Next.js pages, you can update static pages after you have already built the application for production by using incremental static regeneration. To use ISR, you define the revalidate property in the GetStaticProps implementation for that page.
Are the publish webhooks and constant builds / deploys necessary? Or are they just a starting point, after which we add ISR where needed in order to reduce or completely eliminate the constant builds and deploys?
| |
Along with the approaches you have tried, as you mentioned in the question, I would suggest you add HTTPOnly flag as appropriate for your cookies too. Add this to your web.config file.
<system.web>
...
<httpCookies httpOnlyCookies="true" requireSSL="true" />
...
</system.web>
References:
https://andrewwburns.com/2016/10/21/secure-your-sitecore-cookies/
https://learn.microsoft.com/en-us/answers/questions/179172/implement-domain-http-only-and-secure-cookie-attri
Hope this will work.
|
How to make the ASP.NET_SessionId cookies id as a secure
We are using Sitecore 8.2 and We are doing the pen test and reports showing ASP.NET_SessionId is not enabled as a secure.
I had tried the below things in web.config file but this is not working properly.
<httpCookies requireSSL="true" />
And in <forms> set requireSSL too.
<forms name=".ASPXAUTH" cookieless="UseCookies" requireSSL="true" />
Is there any other possible way to change the SSL true for the cookies?
| |
It's all really well explained in the article here:
https://navansitecorenotes.blogspot.com/2023/08/sitecore-1031-config-file-includes.html
In shortcut:
Sitecore 10.3.1 Sitecore.config has a new alwaysExcludeVirtualFolder setting for urlBuilder. It's same with the hotfix.
This doesn't well with 10.3.0 libraries - make sure that if you reference right version of libraries (either from 10.3.1 or from the hotfix), you don't override then again with 10.3.0 libraries while publishing the project.
Ideally, upgrade the whole project to 10.3.1 and use 10.3.1 nuget libraries.
|
Sitecore 10.3 error after security bulletin installation- Could not find property 'alwaysExcludeVirtualFolder'
Recently I installed security bulletin https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1002844 for Sitecore 10.3.
After that I am getting below error in my docker instance.
Could not find property 'alwaysExcludeVirtualFolder' on object of type: Sitecore.Links.UrlBuilders.DefaultItemUrlBuilderOptions
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.InvalidOperationException: Could not find property 'alwaysExcludeVirtualFolder' on object of type: Sitecore.Links.UrlBuilders.DefaultItemUrlBuilderOptions
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:
[InvalidOperationException: Could not find property 'alwaysExcludeVirtualFolder' on object of type: Sitecore.Links.UrlBuilders.DefaultItemUrlBuilderOptions]
Sitecore.Configuration.DefaultFactory.AssignProperties(Object obj, Object[] properties) +2356
Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper) +641
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +326
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.GetConstructorParameters(XmlNode configNode, String[] parameters, Boolean assert) +161
Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert) +114
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +163
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert) +703
Sitecore.Links.LinkProvider.Initialize(String name, NameValueCollection config) +105
Sitecore.Configuration.DefaultFactory.GetProviders(List`1 nodes) +596
Sitecore.Configuration.DefaultFactory.GetProviders(String rootPath, TProvider& defaultProvider) +323
Sitecore.Configuration.ProviderHelper`2.ReadProviders() +75
Sitecore.Configuration.ProviderHelper`2.get_Provider() +116
Sitecore.Links.DefaultLinkManager.ParseRequestUrl(HttpRequest request) +42
Sitecore.Web.RequestUrl.Parse(HttpRequestBase request) +123
Sitecore.Pipelines.HttpRequest.HttpRequestArgs.Initialize() +31
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +118
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) +236
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
Sitecore.Web.RequestEventsHandler.OnBeginRequest(HttpContextBase context) +172
Sitecore.Nexus.Web.HttpModule.HttpApplication_BeginRequest(Object sender, EventArgs e) +121
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +223
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +232
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +100
Though I doubt that security bulletin caused this error but I am not sure.
Does anybody else have this issue? Any idea about this error?
| |
By default Solr won't store anything for null value so you can try wildcard character "*".
I have tested below example and its working.
You need to make sure that _source field exists in Solr. Also, since all fields in Solr are in lowercase so you need to change the case from _Source to _source.
$FilterCriteria = @(
@{Filter = "Equals"; Field = "_source"; Value = "*"; },
@{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Website/sitex" }
)
$itemsToProcess = Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria -First 10 | Initialize-Item
|
Find-Item and the _Source field
Trying use Find-Item to get all items where _Source has a value set. Normally the _Source is null, so I thought that this would be sufficient - check for $null with -Invert set:
$FilterCriteria = @(
@{Filter = "Equals"; Field = "_Source"; Value = $null; Invert=$true },
@{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Website/sitex" }
)
$itemsToProcess = Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria -First 10 | Initialize-Item
It isn't working... Then I thought that I could use "contains" as filter for _Source-field, as the field starts with a "sitecore..."-string if set:
$FilterCriteria = @(
@{Filter = "Contains"; Field = "_Source"; Value = "sitecore" },
@{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Website/sitex" }
)
$itemsToProcess = Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria -First 10 | Initialize-Item
Nothing seems to be working on the "_Source"-field - any clues to make this work?!?
| |
You don't need any separate license file to run XM Cloud in your local environment. All you need access to the XMCloud with your account, and your account must be an admin account. While doing the setup you need to login using powershell script, that will verify your access.
|
How can I validate if my license.xml supports XM Cloud?
I have a partner license.xml file for Sitecore 10, is there a way to quickly tell just by looking at the license.xml content if XM Cloud is supported? In the past there was Sitecore.JSS but I am not sure if this is still the case now as I cannot see this in my license?
| |
To solve this error, you should do the following.
Check if you have enabled Sitecore.Services.GraphQL.Content.Master.config and deploy it to the Sitecore instance.
Now access with https://<your-sitecore-instance>/sitecore/api/graph/items/master
Finally check with your create item query and see if it should work.
Hope this helps.
|
GraphQL.ExecutionError: Schema is not configured for mutations
I am using Sitecore 10.3 SXA Headless and using NextJS Page Router for my Front-end. Basically, I want to create an item by using graphQL mutation method. I have followed this stackexchange issue and also added this below shown configuration as mentioned in the answer,
<configuration>
<sitecore>
<pipelines>
<owin.cookieAuthentication.validateIdentity>
<processor type="Sitecore.Owin.Authentication.Pipelines.CookieAuthentication.ValidateIdentity.ValidateSiteNeutralPaths, Sitecore.Owin.Authentication">
<siteNeutralPaths hint="list">
<path hint="graphql">/sitecore/api/graph/items/</path>
</siteNeutralPaths>
</processor>
</owin.cookieAuthentication.validateIdentity>
</pipelines>
</sitecore>
</configuration>
I have created templates and fields as required and added the GraphQL query as mentioned,
mutation CreateItem {
createItem(
name: "ExampleItem"
template: "{1706CEB1-318A-4D71-A1B8-6FCCEA238762}"
parent: "{27ACB186-4F20-44E8-BD94-8C1C73F97529}"
language: "en"
fields: [
{ name: "Title", value: "'Example Item'" }
{ name: "Text", value: "'This is an example item created with GraphQL'" }
]
) {
path
}
}
but still I am facing some issue in the GraphQL Edge Playground, which says...
{
"errors": [
{
"message": "GraphQL.ExecutionError: Schema is not configured for mutations ---> GraphQL.ExecutionError: Schema is not configured for mutations\r\n at GraphQL.Execution.ExecutionHelper.GetOperationRootType(Document document, ISchema schema, Operation operation)\r\n at GraphQL.Execution.ExecutionStrategy.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at GraphQL.DocumentExecuter.<ExecuteAsync>d__8.MoveNext()\r\n --- End of inner exception stack trace ---",
"extensions": {
"code": "EXECUTION_ERROR"
}
}
]
}
Btw, I am a newbie in Sitecore and JSS, thanks
| |
Index name is not passed OOTB to SchemaPopulateHelper class.
However there is a workaround using Sitecore Switcher class.
First create a class that inherits from mentioned above Switcher class with PopulateManagedSchemaArgs type. This class does not need any method. It should be like:
public class PopulateManagedSchemaArgsSwitcher
: Switcher<Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.PopulateManagedSchemaArgs>
{
}
Next create 2 classes implementing PopulateManagedSchemaProcessor, one that will enter the switcher with current PopulateManagedSchemaArgs, and one that will exit the switcher:
public class EnterPopulateManagedSchemaArgsSwitcher : PopulateManagedSchemaProcessor
{
public override void Process(PopulateManagedSchemaArgs args)
{
PopulateManagedSchemaArgsSwitcher.Enter(args);
}
}
public class ExitPopulateManagedSchemaArgsSwitcher : PopulateManagedSchemaProcessor
{
public override void Process(PopulateManagedSchemaArgs args)
{
PopulateManagedSchemaArgsSwitcher.Exit();
}
}
Then create your CustomPopulateHelper class that will override default SchemaPopulateHelper class, and in the GetAllFields method it will read index and core names from the switcher:
public class CustomPopulateHelper : SchemaPopulateHelper
{
public CustomPopulateHelper(SolrSchema solrSchema) : base(solrSchema)
{
}
public override IEnumerable<XElement> GetAllFields()
{
var args = PopulateManagedSchemaArgsSwitcher.CurrentValue;
var indexName = args?.Index?.Name;
var cores = args?.Cores?.ToList();
var baseFields = base.GetAllFields().ToList();
if (indexName == "my_custom_index")
{
baseFields.Add(CreateField("my_custom_field", "text_general", false, true, false, false, false, false, false, false));
}
return baseFields;
}
}
From what I can see, there is always single core in args.Cores and that core name is equal to args.Index.Name. I'm sure there may be specific case when it will be different, but I'm not sure when and why.
Now it's time for factory, that will create your CustomPopulateHelper instead of default one:
public class CustomPopulateHelperFactory : IPopulateHelperFactory
{
public ISchemaPopulateHelper GetPopulateHelper(SolrSchema solrSchema)
{
return new CustomPopulateHelper(solrSchema);
}
}
And the last thing is config file which binds everything together:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
<sitecore role:require="Standalone or ContentManagement or ContentDelivery" search:require="solr">
<pipelines>
<contentSearch.PopulateSolrSchema>
<processor type="Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.ResolveCoreNames, Sitecore.ContentSearch.SolrProvider" />
<processor
type="MyAssembly.MyNamespace.EnterPopulateManagedSchemaArgsSwitcher, MyAssembly"
patch:before="processor[@type='Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.PopulateFields, Sitecore.ContentSearch.SolrProvider']">
</processor>
<processor type="Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.PopulateFields, Sitecore.ContentSearch.SolrProvider">
<param
type="MyAssembly.MyNamespace.CustomPopulateHelperFactory, MyAssembly"
patch:instead="*[@type='Sitecore.ContentSearch.SolrProvider.Factories.DefaultPopulateHelperFactory']"/>
</processor>
<processor
type="MyAssembly.MyNamespace.ExitPopulateManagedSchemaArgsSwitcher, MyAssembly"
patch:after="processor[@type='Sitecore.ContentSearch.SolrProvider.Pipelines.PopulateSolrSchema.PopulateFields, Sitecore.ContentSearch.SolrProvider']">
</processor>
</contentSearch.PopulateSolrSchema>
</pipelines>
</sitecore>
</configuration>
And that's it, your custom field will be added to the managed-schema of the index:
|
How can get current index name while adding a custom fields to a Solr schema in using 'IPopulateHelperFactory' Sitecore 10.3
I am adding custom fields in solr schema in Sitecore 10.3. But it will be for specific index.
How can i get index name in the class which is inherited from IPopulateHelperFactory refer this link to add custom code
| |
Ideally, when there is no language version, 404 Page Not Found status should be returned.
Long long time ago I wrote a blog post with sample code which sets Sitecore.Context.Item to null if the item doesn't have language version.
You can find it in wayback machine:
https://web.archive.org/web/20150324234154/http://www.cognifide.com/blogs/sitecore/sitecore-displaying-pages-without-a-language-version/
In shortcut - register your processor after ItemResolver or some other custom item resolvers that you have in your application:
<processor type="Sitecore.Pipelines.HttpRequest.ItemResolver, Sitecore.Kernel"/>
<processor type="MyAssembly.MyNamespace.ItemLaguageVersionValidator, MyAssembly" />
And in the code check number of versions in current language like that:
public class ItemLaguageVersionValidator : Sitecore.Pipelines.HttpRequest.HttpRequestProcessor
{
public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args)
{
// don't change the flow of Experience Editor or Preview mode
if (!Context.PageMode.IsNormal)
return;
if (Context.Item != null
&& Context.Item.Paths.IsContentItem
&& Context.Item.Versions.Count == 0)
{
Log.Info($"Not existing language '{Context.Item.Language}' request for item '{Context.Item.Paths.FullPath}'", this);
Context.Item = null;
}
}
}
|
Inactive language version visits on Sitecore 9.3 website and potential security implications
Recently, we received a website visit report indicating a significant number of non-existent language versions visits on our Sitecore 9.3 website (see to the image below).
We have only enabled the English version, so we are concerned whether these records are a result of external tools attacking our site or if this is a normal occurrence. This issue started occurring since last month.
We would greatly appreciate guidance on how to prevent such occurrences and ensure the security of our website. Please provide any advice or recommendations you may have.
What is the recommended approach for handling inactive language versions on Sitecore 9.3? Currently, when accessing an inactive language version, it returns an empty header using the default layout, which is not considered best practice. Please provide guidance on how to handle this situation appropriately.
| |
Try out below to resolve the issue.
1. Check The Language Definition Config
Navigate to the App_Config folder wwwroot\[your site]\App_Config and look for the LanguageDefinitions.config. If it is missing, you will need to reinstall it.
Open up the config file, and search for your language id and region. If you can't find it, reinstall this file.
2. Restart CM Server
If the Sitecore items and the config file exist, the last thing to do is restart CM and try publishing again.
Credit: https://www.getfishtank.com/blog/fix-disappearing-language-error-in-sitecore
Hope it helps!
|
Language is not displaying published item in Sitecore 10.2
We are trying to publish the item.But the language is not displaying in the popup. The langauge is already there in system/lanaguages. But it is still not displaying.
| |
You inherit from CustomizeRenderingProcessor but you never call any base method. It means you don't need this inheritance.
Instead, inherit from Sitecore.Mvc.Pipelines.MvcPipelineProcessor<Sitecore.Personalization.Mvc.Pipelines.Response.CustomizeRendering.CustomizeRenderingArgs> like:
public class DatasourceResolver : MvcPipelineProcessor<Sitecore.Personalization.Mvc.Pipelines.Response.CustomizeRendering.CustomizeRenderingArgs>
{
public override void Process(CustomizeRenderingArgs args)
{
var _rootPath = Sitecore.Context.Site.SiteInfo.RootPath.ToString();
if (!string.IsNullOrEmpty(_rootPath) && _rootPath.StartsWith("/sitecore/content/SiteFolder/SiteCollections"))
{
var rendering = args.Rendering;
var renderingDatasourceArgs = new ResolveRenderingDatasourceArgs(rendering.DataSource);
CorePipeline.Run("resolveRenderingDatasource", renderingDatasourceArgs);
rendering.DataSource = renderingDatasourceArgs.Datasource;
}
}
}
|
This "Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering" is not found in Sitecore.Mvc.Analytics10.0.3
We are in the process of converting Sitecore 9.0.2 MVC project to Sitecore 10.0.3. The following code was used to convert the shorthand like site:$datafolder/Home/Banne to the absolute path in the context of the current location. This way we were able to copy and paste the renderings without making changes in the datasource path.
After moving this code to Sitecore 10.0.3 we are not able to find the following namespace in the Sitecore.Mvc.Analytics.dll version 10.0.3
Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering
<mvc.customizeRendering>
<processor type="Common.Pipelines.mvc.customizeRendering.DatasourceResolver, Common" patch:after="*"/>
</mvc.customizeRendering>
using Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering;
using Sitecore.Pipelines;
using Sitecore.Pipelines.ResolveRenderingDatasource;
namespace Common.Pipelines.mvc.customizeRendering
{
public class DatasourceResolver : CustomizeRenderingProcessor
{
public override void Process(CustomizeRenderingArgs args)
{
var _rootPath = Sitecore.Context.Site.SiteInfo.RootPath.ToString();
if (!string.IsNullOrEmpty(_rootPath) && _rootPath.StartsWith("/sitecore/content/SiteFolder/SiteCollections"))
{
var rendering = args.Rendering;
var renderingDatasourceArgs = new ResolveRenderingDatasourceArgs(rendering.DataSource);
CorePipeline.Run("resolveRenderingDatasource", renderingDatasourceArgs);
rendering.DataSource = renderingDatasourceArgs.Datasource;
}
}
}
}
| |
I have faced similar issue where my regex wasnt working as expected in custom validator. For now you can try recreating same validator in your solution just to debug and then see if all parameters are received as expected.
In my case, regex wasn't populated in the expected property. So I made change in code a bit like this,
//Sitecore namespace - Sitecore.ExperienceForms.Mvc.Models.Validation
public class CustomRegularExpressionValidation : ValidationElement<RegularExpressionParameters>
{
public override void Initialize(object validationModel)
{
base.Initialize(validationModel);
if (validationModel is StringInputViewModel stringInputViewModel)
this.Title = stringInputViewModel.Title;
// This was not evaluating as expected
//this.RegularExpression = this.Parameters?.RegularExpression ?? string.Empty;
// so added this
this.RegularExpression = this.ValidationItem.Parameters ?? string.Empty;
}
}
Regex not working in Sitecore Forms
Hope this helps !!
|
Sitecore Forms Checkbox List Validation Issues
Using the suggestions from the following post, I made a custom validation for a checkbox list on a form using the Sitecore Forms Builder. However, when I click the checkbox I get the error message ("click the checkbox!") and I cannot submit the form despite the checkbox being checked.
The form is using a checkbox list and is set to required. I've been having an issue that despite the checkbox being checked, and when submitting the form, Sitecore thinks that the checkbox has not been checked no matter what I do.
In the validations I have the following:
Type: Sitecore.ExperienceForms.Mvc.Models.Validation.RegularExpressionValidation,Sitecore.ExperienceForms.Mvc
Message: Check the field!
Parameters: {"regularExpression":"^/on$/"} (I also tried with true)
The checkbox list is set to required on the form.
I have set my checkbox list option to use this custom validator as well and ensure it was set on my form.
| |
To achieve the desired result, the Find-Item function alone won't suffice; additional logic is required.
Here's a working example:
$indexName = "sitecore_web_index"
$criteria = @(
@{Filter = "Contains"; Field = "industry_sm"; Value = "{7451A225-6450-4D26-BE04-624FD2E63B76}" },
@{Filter = "Contains"; Field = "service_sm"; Value = "{0670EE3C-1D07-4172-9ADB-19127D90C180}" }
)
# Find items matching the criteria and group them by item ID
$list = Find-Item -Index $indexName -Criteria $criteria | Group-Object -Property ItemId
# Initialize only one language version per item (preferably English)
$filteredList = $list | % { $_.Group | Sort-Object { if ($_.Language -eq "en") { 0 } else { 1 } } | Select-Object -First 1 | Initialize-Item }
# $filteredList now contains one language version per item
foreach($filteredItem in $filteredList){
Write-Host "Item ID: $($filteredItem.ID), Language: $($filteredItem.Language), Name: $($filteredItem.Name)"
}
|
Get Only one language version per item by using Find-Item
I am using a PowerShell script given below
$indexName = "sitecore_web_index"
$criteria = @(
@{Filter = "Contains"; Field = "industry_sm"; Value = "{7451A225-6450-4D26-BE04-624FD2E63B76}" },
@{Filter = "Contains"; Field = "service_sm"; Value = "{0670EE3C-1D07-4172-9ADB-19127D90C180}" }
)
$list = Find-Item -Index $indexName -Criteria $criteria | Initialize-Item
It returns a list of all present language versions per item. Is it possible somehow through the script to make it return only one language version per item (English by default or other if English is not present)?
| |
This is a known issue in sitecore forms.
Please follow the below workaround.
As you can see the fxb.30da5a39-2ca9-487a-89c5-5b9f4328569f.Fields[2a03d066-f884-4106-8bf3-b5c18e79e287] field is my Single Line Text field. Now if I wanted to post the form without the required field data, then I’d just change the posted form data to my liking:
https://www.maartenwillebrands.nl/2021/07/28/sitecore-forms-bypassing-validation-and-overposting-viewmodels/
|
Upload File is expecting file even after disabled
I have a mandatory file upload field in Sitecore forms that should be disabled based on a condition of a dropdown field. Even after making the mandatory upload field optional, Sitecore is still expecting a file to be uploaded.
Is there any way to overcome this issues? Kindly find the screenshot for reference.
| |
In Sitecore 10.3 Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering logic is moved to Sitecore.Personalization.Mvc dll
Sitecore.Personalization.Mvc.Pipelines.Response.CustomizeRendering use this
|
Sitecore.Mvc.Analytics 10.3 doesn't contain a definition for Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering
using Sitecore.Data.Items;
using Sitecore.Mvc.Analytics.Pipelines.Response.CustomizeRendering;
using Sitecore.Pipelines;
using Sitecore.Pipelines.ResolveRenderingDatasource;
public class CustomMVCResolveRenderingDataSource : CustomizeRenderingProcessor
{
public override void Process(CustomizeRenderingArgs args)
{
var rendering = args.Rendering;
//Get the Site Item
var contextSiteItem = GetSiteItem(Context.Item);
if (!string.IsNullOrEmpty(rendering.DataSource) && contextSiteItem != null)
{
if (rendering.DataSource.Contains("$SiteName"))
{
rendering.DataSource = rendering.DataSource.Replace("$SiteName", contextSiteItem.Name);
Item sourceItem = Context.Database.GetItem(rendering.DataSource);
if (sourceItem != null)
{
rendering.DataSource = sourceItem.ID.ToString();
}
}
}
//Initialize the resolved DataSource to ResolveRenderingDatasourceArgs
var renderingDSArgs = new ResolveRenderingDatasourceArgs(rendering.DataSource);
CorePipeline.Run("resolveRenderingDatasource", renderingDSArgs);
rendering.DataSource = renderingDSArgs.Datasource;
}
}
| |
Here is a handy script that will let you reindex any item on any specific index. You can also add any specific logic and it will index the items for you.
$options = @{}
[Sitecore.ContentSearch.ContentSearchManager]::Indexes | Foreach-Object { $options.Add($_.Name, $_.Name) }
$props = @{
Parameters = @(
@{Name="indexName"; Title="Choose an index"; Options=$options; Tooltip="Choose one."}
)
Title = "Index selector"
Description = "Choose an index."
Width = 300
Height = 300
ShowHints = $true
}
$result = Read-Variable @props
if ($result -eq "ok") {
$index = [Sitecore.ContentSearch.ContentSearchManager]::GetIndex($indexName)
}
Close-Window
Get-ChildItem -path "/sitecore/content/Home/" -language en-Us -Recurse | Where-Object { $_.TemplateName -eq 'Product' } | ForEach-Object {
if([string]::IsNullOrEmpty($_."Any Field")){
write-host $_.Name " SKIPPED"
}
else{
write-host $_.Name $_.Paths.FullPath
[Sitecore.ContentSearch.Maintenance.IndexCustodian]::Refresh($index, [Sitecore.ContentSearch.SitecoreIndexableItem]$_)
}
}
Ref: https://cmsxperience.com/2023/01/05/sitecore-powershell-script-to-reindex-a-specific-item-on-a-specific-index/
Hope this helps.
|
Rebuild SOLR index of an item using sitecore powershell
I am trying to rebuild the SOLR indexes of a particular Sitecore item using Sitecore Powershell. I have a list of Sitecore items and I want to rebuild indexes for all items in the list. is there any way to do this?
| |
Once you’ve generated your token, you need to pass your API Token in the headers for your request. If you look at the bottom of the page you will see a HTTP HEADERS button that will give you a pane used to add those to your request. You add them in the following format,
{
"X-GQL-Token": "XXX_YOUR_TOKEN_HERE_XXX"
}
Once this has been added you will be able to query your data and see results returned.
Reference:
https://robearlam.com/blog/how-to-set-the-experience-edge-auth-token-with-apollo-graphql
https://konabos.com/blog/querying-sitecore-experience-edge-using-the-graphql-endpoint
Hope it helps!
|
Unable to query graphql in Delivery API playground
I am trying to use Graphql playground using the Delivery API endpoint and I am getting an error
{
"error": "Unexpected end of JSON input"
}
I am using Edge token as an API key.
Can anyone guide me?
Additionally, I have set Sitecore_GraphQL_ExposePlayground="true" in the XM cloud variable tab
| |
You can run the front application locally and connect to XM Cloud for your CM. To do this you will need to:
make a copy of the .env file and call it .env.local
Edit these variable values:
SITECORE_API_KEY - this needs to be your API key from /sitecore/settings/services/api keys/xmcloudpreview - use the item ID.
GRAPH_QL_ENDPOINT - set to https://<url to your cm instance>/sitecore/api/graph/edge
JSS_APP_NAME - the name of your site/app name from the settings item
Run the application by going to the root of your next.js application and running:
npm run start:connected
This will run the app on http://localhost:3000 and be connected to the preview end point on your CM instance.
If you want to run the full CM instance locally, Docker is your only option.
Docs are here: https://doc.sitecore.com/xmc/en/developers/xm-cloud/walkthrough--connecting-the-next-js-application-directly-to-the-experience-edge-endpoint.html
Although the above docs connect your application to Experience Edge directly vs the preview end point. IMO, for development you should connect to the preview end point as it saves time when you don't have to publish items to get access to them.
|
Sitecore XM Cloud Local Setup without Docker
Is there an alternative way to setup Sitecore XM Cloud local development environment without Docker? (Hitting lot of company security issues with Docker setup)
| |
So the answer to this was right under my nose the whole time, but to anyone that struggles with this in the future...
While I checked to makes sure the English language itself had been published to the Web db. I did not notice that the system/languages folder item did not have a version.
Once I added an English version for the system/languages folder and published it everything thing else published correctly when doing a Site Publish.
|
Sitecore 10.2 Smart Publish Not Publishing Versions to CD Server
I am currently running into a strange problem with our 10.2 environment that we are upgrading from 9.0.2. It has previously been working. However, when we did our latest database migration from existing production (9.0.2) to our 10.2 environment. We started running into a problem when doing a "Site Publish" where Sitecore will first publish the content to our CD environment and then remove our only version (english) from those items before completing the Site Publish.
This results the client facing CD environment to virtually have none of its content - mostly just blank pages. Checking the content in the web DB and it looks like the items are physically there - just no versions are available and get the message:
The current item does not have a version in "English : English".
To create a version, click Add a New Version or click Add on the Versions tab.
This happens for all content and there are no custom pipeline processors manipulating items... Watching the trace during live view/logs doesn't reveal anything out of the ordinary.
Furthermore, while the publish is taking place, you can see in the web db that the versions are there. Then at the very end right before the publish of master to web completes it removes all the item versions
I was wondering if anyone has run into this problem before or might have some suggestions on what to do to fix this?
| |
Microsoft AZURE Support team pointed out the problem is Azure Front Door is not able to cache these files because of the following reasons,
From the origin(renderinghost appservice) is setting cache header as "public max-age=0" for all static files.
Also, compression should happen at the Azure Front Door and not from the origin(renderinghost appservice). Currently, our rendering host
doing compression.
Then we ended up fixing those headers from the origin(renderinghost appservice) application layer NODEJS headless proxy template. We did with the below option and options may vary
Disable compression from the rendering host NODEJS headless proxy. You can find this line responsible for compression "server.use(compression())", You can disable it as like below,
// enable gzip compression for appropriate file types
if (process.env.AAAA_DISABLE_COMPRESSION === "true") {
server.use(compression({ filter: shouldCompress }));
function shouldCompress() {
return false;
}
}else{
server.use(compression());
}
Setting up the cache response header from the rendering host NODEJS headless proxy. You can find these middleware lines from the template "server.use('/dist'" change it to below like this,
server.use(
'/dist',
express.static(reqPath, {
fallthrough: false, // force 404 for unknown assets under /dist
// Added for handling cache header
setHeaders: function(res) {
if (process.env.AAAA_ENABLE_DIST_FOLDER_PUBLICHCACHE === "true") {
res.setHeader('cache-control', 'public, max-age='+(process.env.AAAA_DIST_FOLDER_PUBLICHCACHE_MAXAGE||'31536000'));
// Added for remove compression header
res.removeHeader('Accept-Encoding');
}
}
})
);
Now from the origin level cache max age is increased & compression disabled. Post Azure Front Door can cache these static resources!
|
Sitecore RenderingHost pointing to AzureFrontDoor is serving static files like CSS, JSS slowly and sometimes it gives ERR_HTTP2_PROTOCOL_ERROR
We are using Sitecore version 10.3.0 with JSS and server-side rendering using a Node.js headless proxy. All of our resources are hosted in Azure.
Our Azure Front Door (aaaa.afd.net) is pointed to the rendering host (aaaa-renderinghost.azurewebsites.net).
We have a CDN (aaaa-cdn.azureedge.net) for media files, which is also pointed to the rendering host (aaaa-renderinghost.azurewebsites.net). In Sitecore's SitecoreCD, we have enabled CDN configuration, and this CDN URL is pointed there. There are no issues with media files; they load as expected.
The overall setup is almost a typical setup of a traditional (Non-Headless) managed cloud instance with Azure Front Door and CDN. The only difference from the traditional (Non-Headless) setup is that we have pointed the CDN to the Rendering Host instead of the SitecoreCD.
Please note, below the cache setup,
In Azure Front Door, caching is enabled with "Cache every unique URL," default cache period, and compression enabled.
In the CDN, compression is enabled for all formats.
Below overall error summary,
When we directly access app services, all the static files such as CSS, JSS, and favicon load. However, these files do not load from Azure Front Door, and we receive an error in the browser console with ERR_HTTP2_PROTOCOL_ERROR.
No logs from the rendering host and in Azure Front Door log all these files are getting 503 status!
When we disable the cache from FrontDoor, all static files are loaded as expected from Azure Front Door!
| |
Try with powershell variable $SitecoreDataFolder to retrieve path related to App_Data, as from looking into the issue it seems its not getting the path you are specifying. If it doesn't work then do post your script here.
|
Not able to Save data in physical file while using docker through Sitecore Powershell
I'm new to PowerShell scripts and want to create items in Sitecore's Shared Data folder in a Json file and save the uploaded Json file in the App_Data directory's location. I tried using fullpath and relative path in the script, but it does not function and returns an error.
Please help me.
| |
Below answer for react get starter template!
Disable it from the client-side template
We can disable the client-side template dictionary service call from the below file.
Go to this file => \src\index.js
Comment as like below!
/*
App Rendering
*/
// initialize the dictionary, then render the app
// note: if not making a multlingual app, the dictionary init can be removed.
// i18ninit(initLanguage).then(() => {
// HTML element to place the app into
const rootElement = document.getElementById('root');
renderFunction(
rootElement,
<AppRoot
path={window.location.pathname}
Router={BrowserRouter}
graphQLClient={graphQLClient}
ssrState={__JSS_STATE__}
/>
);
// });
Now you can check refreshing the page, dictionary service calls will not initiate.
Disable it from the SSR(node-js-headless-proxy) template
If you are using server-side rendering(node-js-headless-proxy), Then you have to disable it from the SSR template as well.
Go to this file => \src\ssr-proxy\src\config.ts
Comment as like below & give an empty return statement like this.
Note: This will not affect your multilingual language calls. No need to worry.
return {};
//Disabled the dictionary call
// return dictionaryService.fetchDictionaryData(language).then((phrases) => {
// const viewBag = {
// dictionary: phrases,
// };
// return viewBag;
// });
Now you can check the final hosted version of our website. Dictionary calls will be completely disabled. At the same time, you can consume layout services per language context!
|
Disable dictionary service call in get starter JSS/react template
I am using the Getting Started template, and I can see the dictionary call is initiated by default.
How to disable this call?
| |
So just to clarify you are serializing entities from Content Hub. If so you need to reference the entity definition:
# Pulling all entities for an entity definition
ch-cli serialization pull entity --definition <entity definition name>
https://doc.sitecore.com/ch/en/developers/cloud-dev/integration-tools--serialization.html
|
Serialize content hub pages
We are using Content Hub 4.2. We want to serialize pages in the content hub. Is there any specific command to achieve this?
Also, while trying to serialize entities getting an error as The specified resources were not found.
We are able to serialize entity definitions and option list using the following commands-
ch-cli serialization pull ed
How can we resolve this?
| |
Though you are calling it Multilingual sites, they are setup as multisite since you have different Home Nodes for each language. (I would suggest you to not to alter SXA's native site Site structure to add multiple Home nodes.)
You can create multiple sites instead. Like -
Public Site DE > Home
Public Site FR > Home
Public Site EN > Home
And for each site, create a site definition item.
All site definitions can have same host name but with different virtual folder and language.
For Public Site DE, Site definition item will have -
Host Name : www.mydomain.com
Virtual folder : de-de
Language : de-DE
This should work the way you need.
Ideally, you should not have 3 Home nodes if you want to implement multilingual site.
You should create just 1 Home node instead.
Add languages Enabling Multilingual Support with SXA
Create all necessary language versions of your items as I see same
items under each language Home Node
Make use of Language Embedding attribute in Site Definition item. In your case, you can set it to Always Site Definition in SXA
Hope this helps.
|
How to setup a multilingual site with the same domain but different home items
I have a single SXA site with multiple language versions like English,German,French,Italian etc.
Now, I have following requirement :
Each language version must have it's own content node like below with same set of pages inside them with EN-Home will have only English language, DE-Home with only German language and so on.
Now my url must look like
www.mydomain.com/en-us
www.mydomain.com/de-de
www.mydomain.com/fr-fr
I tried adding Site Groupings like below(by selecting respective content node with language) but it does not resolve properly.
Any suggestions on how to make this work would be really helpful.
| |
You can extend a Download script (/sitecore/system/Modules/PowerShell/Script Library/SPE/Maintenance/Media Library Maintenance/Content Editor/Context Menu/Download) which is provided out of the box and store your file under SitecoreDataFolder (/App_Data).
So you can create a zip file for all the media items and store them in SitecoreDataFolder. Comment out the download and remove the zip code at the end of the script. So it will stay there in /App_Data folder.
function ZipItems( $zipArchive, $sourcedir )
{
Set-Location $sourcedir
[System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, `
Culture=neutral, PublicKeyToken=31bf3856ad364e35") > $null
$ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipArchive, `
[System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite)
$items = @(Get-Item $sourceDir) + (Get-ChildItem -recurse $sourceDir)
[byte[]]$buff = new-object byte[] 40960
$i = 0;
ForEach ($item In $items) {
$i++
if([Sitecore.Resources.Media.MediaManager]::HasMediaContent($item)){
$mediaItem = New-Object "Sitecore.Data.Items.MediaItem" $item;
$mediaStream = $mediaItem.GetMediaStream();
$fileName = Resolve-Path -Path $item.ProviderPath -Relative
$fileName = "$fileName.$($item.Extension)".Replace("\","/").Replace("./","/");
"Added: $fileName"
Write-Progress -Activity "Zipping Files " -CurrentOperation "Adding $fileName" -Status "$i out of $($items.Length)" -PercentComplete ($i *100 / $items.Length)
$partUri = New-Object System.Uri($fileName, [System.UriKind]::Relative)
$partUri = [System.IO.Packaging.PackUriHelper]::CreatePartUri($partUri);
$part=$ZipPackage.CreatePart($partUri, "application/zip", [System.IO.Packaging.CompressionOption]::Maximum)
$stream=$part.GetStream();
do {
$count = $mediaStream.Read($buff, 0, $buff.Length)
$stream.Write($buff, 0, $count)
} while ($count -gt 0)
$stream.Close()
$mediaStream.Close()
}
}
$ZipPackage.Close()
}
$location = get-location
$time = Get-Date -format "yyyy-MM-d_hhmmss"
$zipName = Split-Path -leaf $location | % { $_ -replace " ", ""}
$zipPath = "$($SitecoreDataFolder)\$zipName-$time.zip"
ZipItems $zipPath $location
Download-File -FullName $zipPath > $null
Remove-Item $zipPath
Close-Window
Refer this article that provide more context: https://www.nehemiahj.com/2022/05/download-multiple-media-files-from.html
Hope it helps!
|
How to download media item to SitecoreTempFolder?
I'm wanting to clean-up the media library, I have a script that outputs unused media library IDs. I then want to grab the media item associated with these IDs and download them to a temporary folder (i.e. SitecoreTempFolder). I've tried Send-File and Out-Download but these both store items to the local download folder which is not viable.
I'm just after the actual media item/file and not the Sitecore item. I have also attempted to use the move-item/copy-item but these cannot transfer between Sitecore and local/temp folders.
Many thanks in advance for any advice!
| |
Please make sure you are following the correct documentation and using the correct github repository.
The xmcloud work differently and you need to use Sitecore CLI for deployment.
Getting Started: https://doc.sitecore.com/xmc/en/developers/xm-cloud/getting-started-with-xm-cloud.html
Deploy: https://doc.sitecore.com/xmc/en/developers/xm-cloud/the-cloud-deployment-command.html
https://doc.sitecore.com/xmc/en/developers/xm-cloud/xm-cloud-deploy-app.html
You can check out the demo from Andy Cohen for deployment on youtube :
https://www.youtube.com/watch?v=a23g2TRUvOI&ab_channel=AndyCohen
I hope it helps
|
JSS deploy config to XM Cloud failed
I'm using Sitecore XM Cloud environment, and I setting up my next.js app to connect to Sitecore editors.
I'm currently following this article.
After setting up the configuration file and run jss deploy config, I got the following error
Error: ENOENT: no such file or directory, mkdir '/App_Config/Include/zzz'
at Object.mkdirSync (node:fs:1390:3)
at module.exports.makeDirSync (/Users/user/Documents/XMCloud/xxx/xxx.XMC.Websites/node_modules/fs-extra/lib/mkdirs/make-dir.js:23:13)
at deploy (/Users/user/Documents/XMCloud/xxx/xxx.XMC.Websites/node_modules/@sitecore-jss/sitecore-jss-dev-tools/dist/cjs/deploy.js:21:28)
at Object. (/Users/user/Documents/XMCloud/xxx/xxx.XMC.Websites/node_modules/@sitecore-jss/sitecore-jss-cli/dist/cjs/scripts/deploy.config.js:58:45)
at Generator.next ()
at fulfilled (/Users/user/Documents/XMCloud/xxx/xxx.XMC.Websites/node_modules/@sitecore-jss/sitecore-jss-cli/dist/cjs/scripts/deploy.config.js:5:58) {
errno: -2,
syscall: 'mkdir',
code: 'ENOENT',
path: '/App_Config/Include/zzz'
}
This is my scjssconfig.json content
{
"sitecore": {
"instancePath": "",
"apiKey": "<api key>",
"deploySecret": "<deploy secret key>",
"deployUrl": "https://xxx.sitecorecloud.io/sitecore/api/jss/import",
"layoutServiceHost": "https://xxx.sitecorecloud.io/"
}
}
I have 2 questions here
I'm suspecting the error is due to the missing instance path. But I'm using XM Cloud, where can I get the actual path? Do I need to raise Sitecore support to get it?
The sitecoreConfigPath defined in package.json is set to /App_Config/Include/zzz. It is a must to deploy to this folder path?
| |
It appears that you have successfully deployed your JSS VueJS app on Vercel, but you are facing issues, possibly because of missing environment variables. You are correct, environment variables play a crucial role in configuring applications accurately.
You mentioned that your app doesn't have a .env file like the default Sitecore VueJS application. If you're following a tutorial that's focused on Next.js, it might not align perfectly with your VueJS app's requirements.
To identify the VueJS variables you need to set in your Vercel environment, you'll want to consider the configuration needs of your Vue app. Common environment variables for Vue apps might include API endpoints, authentication tokens, or other runtime settings.
On the basis of the above, I can suggest 2 Approaches as below.
Approach 1
Here are the general steps you can follow:
Identify Required Variables: List down the variables your VueJS app needs. These could be API URLs, keys, secrets, or any other configuration values.
Configure Vercel: Go to your Vercel project dashboard and navigate to the settings section. There should be a place to add environment variables. Add the variables you identified in the previous step here.
Accessing Environment Variables in Your App: In your Vue app code, you can access these variables using the process.env object. For example, if you've set an environment variable named VUE_APP_API_URL, you can access it like this: process.env.VUE_APP_API_URL.
As for specific documents or guides, since you're working with VueJS on Vercel, you might not find resources that exactly match your scenario. However, you can look into
Vercel's documentation on environment variables
While it might be more focused on Next.js, the concept of handling environment variables should be similar and might provide valuable insights.
Remember to ensure the variable names you use in Vercel's dashboard (VUE_APP_API_URL for instance) match the ones you reference in your Vue app's code.
Approach 2
To set up environment variables for a VueJS app deployed on Vercel, you can follow these steps:
In your VueJS project, create a .env file in the root directory. This file will store your environment variables.
Open the .env file and define your variables in the format VARIABLE_NAME=variable_value. For example:
API_URL=https://api.example.com
SECRET_KEY=abc123
In your VueJS code, you can access these environment variables using process.env.VARIABLE_NAME. For example:
const apiUrl = process.env.API_URL;
const secretKey = process.env.SECRET_KEY;
Install the dotenv package by running npm install dotenv in your project directory. This package will load the environment variables from the .env file.
In your VueJS project, create a vercel.json file in the root directory (if it doesn't exist already).
Open the vercel.json file and add the following code to define the environment variables for Vercel:
{
"env": {
"API_URL": "@api-url",
"SECRET_KEY": "@secret-key"
}
}
Deploy your VueJS app to Vercel. Vercel will automatically replace the placeholders (@api-url and @secret-key) with the actual environment variable values defined in the Vercel environment.
By following these steps, you should be able to set up and access environment variables in your VueJS app deployed on Vercel.
If you continue to face issues, don't hesitate to provide more specific details about the problem you're encountering, and I'd be glad to offer further assistance. Good luck, and I hope this might help you and you get your VueJS app up and running as expected!
|
Need Help with VueJS Environment Variables on Vercel: How to Set Up for a JSS VueJS App?
I've successfully deployed my JSS VueJS app on Vercel, but it's not working as expected. I suspect the issue lies in the absence of environment variables, which I know are essential.
Unlike the default Sitecore VueJS application, which uses vue.config.js
, my app doesn't have a .env
file. I attempted to follow this tutorial for nextJS, but unfortunately, it didn't work.
Can anyone help me identify the VueJS variables I need to set in my Vercel environment? If there are any specific documents or guides on this topic, I'd appreciate the pointers. Thank you
| |
If you have setup two separate identity providers in config, then you should just be able to use the Ids of those providers as part of the login paths.
See example below, which uses ADFS and Azure as two separate providers:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<federatedAuthentication>
<identityProviders>
<identityProvider id="SitecoreIdentityServer/IdS4-AzureAd" type="Sitecore.Owin.Authentication.Configuration.DefaultIdentityProvider, Sitecore.Owin.Authentication">
<param desc="name">$(id)</param>
<param desc="domainManager" type="Sitecore.Abstractions.BaseDomainManager" resolve="true" />
<caption>Log in with Sitecore Identity: Azure AD</caption>
<icon>/sitecore/shell/themes/standard/Images/24x24/msazure.png</icon>
</identityProvider>
<identityProvider id="SitecoreIdentityServer/IdS4-WsFederation" type="Sitecore.Owin.Authentication.Configuration.DefaultIdentityProvider, Sitecore.Owin.Authentication">
<param desc="name">$(id)</param>
<param desc="domainManager" type="Sitecore.Abstractions.BaseDomainManager" resolve="true" />
<caption>Log in with Sitecore Identity: ADFS</caption>
<icon>/sitecore/shell/themes/standard/Images/24x24/msazure.png</icon>
</identityProvider>
</identityProviders>
</federatedAuthentication>
<sites>
<site name="your-site-name" loginPage="$(loginPath)your-site-name/SitecoreIdentityServer/IdS4-WsFederation" />
<site name="shell" loginPage="$(loginPath)shell/SitecoreIdentityServer/IdS4-AzureAd" />
</sites>
</sitecore>
</configuration>
Then when you go to either site to login, then it should provide a different redirect URL.
How does your config compare to the example above?
|
Sitecore Identity callback path issue
I have set up 2 identity provider plugins in sitecore identity, one is being used for /sitecore login the other is used for one of our portals to authenticate against. Both use Okta as the IdP, however they are using 2 different instances (one is for internal employees, the other is for application users).
The issue I am having is that when the application users hit Okta and then redirect back to the identity server /signin-idsrv endpoint the identity server falls back to using the employee version of the Okta plugin. Is there something I am missing configuration wise that can solve this issue? I believe the issue is that the identity server does not know which Okta instance is redirecting back to it and so it handles it using the first identity plugin it finds in the config.
I think this might be the issue as both plugins use the same paths currently.
options.CallbackPath = new PathString("/signin-idsrv");
options.SignedOutCallbackPath = new PathString("/signout/callback");
loginPage="$(loginPath)admin-portal/SitecoreIdentityServer/IdS4-OktaGroupPortal"
<configuration>
<sitecore>
<federatedAuthentication>
<identityProvidersPerSites hint="list:AddIdentityProvidersPerSites">
<mapEntry name="admin portal" type="Sitecore.Owin.Authentication.Collections.IdentityProvidersPerSitesMapEntry, Sitecore.Owin.Authentication" resolve="true">
<identityProviders hint="list:AddIdentityProvider">
<identityProvider ref="federatedAuthentication/identityProviders/identityProvider[@id='SitecoreIdentityServer/IdS4-OktaGroupPortal']" />
</identityProviders>
<sites hint="list">
<site>admin-portal</site>
</sites>
<externalUserBuilder type="MLCGP.Security.Feature.Pipelines.CustomExternalUserBuilder, MLCGP.Security.Feature" resolve="true">
<IsPersistentUser>true</IsPersistentUser>
</externalUserBuilder>
</mapEntry>
</identityProvidersPerSites>
<identityProviders>
<identityProvider id="SitecoreIdentityServer/IdS4-OktaGroupPortal" type="Sitecore.Owin.Authentication.Configuration.DefaultIdentityProvider, Sitecore.Owin.Authentication">
<param desc="name">$(id)</param>
<param desc="domainManager" type="Sitecore.Abstractions.BaseDomainManager" resolve="true" />
<caption>Log in with Okta</caption>
<icon>/sitecore/shell/themes/standard/Images/24x24/msazure.png</icon>
<domain>portal</domain>
<enabled>true</enabled>
</identityProvider>
</identityProviders>
<propertyInitializer type="Sitecore.Owin.Authentication.Services.PropertyInitializer, Sitecore.Owin.Authentication">
<maps hint="list">
<map name="name to FullName" resolve="true"
type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication">
<data hint="raw:AddData">
<source name="name"/>
<target name="FullName" />
</data>
</map>
</maps>
</propertyInitializer>
</federatedAuthentication>
</sitecore>
</configuration>
| |
tl/dr is that you can't.
Scheduled tasks don't run within a request context, they run within the context of the shell website defined in the siteDefinition section of the config.
|
Current Host Name for Scheduled Task
Is there any way to determine the host name from within a Sitecore Scheduled Task?
I found that within an ASP.NET MVC page for Sitecore 9.3, I can peer into the current HttpContext via Sitecore.Context.HttpContext.
However, it does not seem possible from within the implementation of a Scheduled Task -- Sitecore.Context.HttpContext just returns null.
| |
With 4.2+ version previous version has now been removed/disabled (Check July 17, 2023 Improvements here), however, the version number is now shown within the user interface of Content Hub.
You need to log in to your Content Hub instance and click on the Manage button in the top right. Scroll down to the bottom of the page and the version is shown here.
If you go to the new Content Hub – Whats new page you can easily find out what release you are on and what that version contains.
Hope it helps!
|
How to check Sitecore Content Hub Version
When I browse https://mysite.sitecorecontenthub.com/api/status as mentioned here, there is a Guid value for the product version property
{
"product_version": "7d2ea05460a1e362117f54876100f2c7b3025314",
"build_date": "2023-08-11T12:59:44+00:00",
"hostname": "abcd-p-001-portal-ui-6cfb8fcdf6-2q74n",
"region_name": null,
"aggregated_service_status_label": "Red",
"index_template_versions": {
"main_template_version": "15000",
"audit_template_version": {
"default_template": "15000"
}
},
"queues": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/queues",
"title": "Status of the message queues"
},
"jobs": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/jobs",
"title": "Status of the processing jobs"
},
"users": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/users",
"title": "Status of the user base"
},
"license": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/license",
"title": "State of your license"
},
"system": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/system",
"title": "Obsolete resource, use the graph, data storage and or search resource instead"
},
"data_storage": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/datastorage",
"title": "Status and statistics of the data storage layer"
},
"media_storage": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/mediastorage",
"title": "Status and statistics of the media storage layer"
},
"search": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/search",
"title": "Status and statistics of the search services"
},
"graph": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/graph{?forceRefresh}",
"title": "Status and statistics of the graph server and its workers",
"templated": true
},
"service_status": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/servicestatus",
"title": "Detailed service status explaining the aggregated status"
},
"publishing": {
"href": "https://mysite.sitecorecontenthub.cloud/api/status/publishing",
"title": "State of publishing functionality"
}
}
UPDATE:
According to this article, for 4.2+ there is no version and just the dates.
If the new version is the date, then how do we check for the latest documentation as the docs are currently categorized by versions.
| |
Make sure the 'Dictionary Domain' is added in the app settings tag of the specific site config.
Refer:
<app name="oneweb"
layoutServiceConfiguration="sxa-jss"
sitecorePath="/sitecore/content/Headless/oneweb"
useLanguageSpecificLayout="true"
dictionaryDomain="{3E599B9D-79AC-4D2E-BF4C-399736F8B94F}"
graphQLEndpoint="/sitecore/api/graph/edge"
inherits="defaults"
serverSideRenderingEngine="http"
serverSideRenderingEngineEndpointUrl="http://localhost:3000/api/editing/render"
serverSideRenderingEngineApplicationUrl="http://localhost:3000"
/>
Snapshot:
|
Unable to Fetch Dictionary Value in Sitecore NextJs App
I am creating a Sitecore Headless application using NextJs and trying to fetch the dictionary value but unable to do so.
Below is the dictionary Item which I have created in Sitecore.
And Below is the code snippet which i am using.
import React, { useEffect, useState } from 'react';
import { dictionaryServiceFactory } from 'lib/dictionary-service-factory';
import {
Item,
Field,
ComponentParams,
ComponentRendering,
} from '@sitecore-jss/sitecore-jss-nextjs';
interface Fields {
Title: Field<string>;
Description: Field<string>;
Products: Item[];
Author: Field<string>;
}
type MultiListProps = {
rendering: ComponentRendering & { params: ComponentParams };
params: { [key: string]: string };
fields: Fields;
index: number;
children: JSX.Element;
};
const Default = (props: MultiListProps): JSX.Element => {
const siteName = 'Headless';
const dictionaryService = dictionaryServiceFactory.create(siteName);
const [headingValue, setGallerydValue] = useState<string | null>(null);
useEffect(() => {
dictionaryService.fetchDictionaryData('en').then(data => {
console.log("Fetched data:", data); // Log the fetched data
if (data && data.Heading) {
setGallerydValue(data.Heading);
}
});
}, []);
return (
<div className="cards">
<div className="component-title">
<h1>{headingValue}</h1>
</div>
</div>
);
};
export default Default;
I am getting null value on webpage. Can anyone help me in this?
| |
I think this is what's happening in your setup:
CM and Publishing Service know about two target databases: web and web2. Every time a publishing job is finished, CM sends a remote event called TargetDataCacheClearEvent and specifies the target database name in its parameters. For a publishing job to the first DB it is web, for the second DB it is web2:
Then, each CD slot will listen to events from the connected web database and process them. This is how it works for Slot 2 CD in your configuration:
it receives a cache clear event for the database with name web2
it tries to get a database with this name and can't find it because the database is called web in the config
as there is no such database, the website can't clear caches for it:
Database database = this._factory.GetDatabase(parameter.EventData.DatabaseName);
if (database == null)
throw new ArgumentOutOfRangeException("targetDatabase", Messages.NoDatabaseSpecified);
try
{
this.ClearCaches(database);
}
catch (Exception ex)
{
PublishingLog.Error(Messages.ErrorOccuredClearingTargetDataCache, ex);
throw;
}
If you check Slot 2 logs, there may be error messages saying that the website is unable to find a database called web2.
In order to fix this problem, I would recommend patching configs on the second slot to add a database with name web2 and switch site configs to use web2 instead of web. Remember to check all places that rely on the database name: indexes, schedulers, etc.
|
CD Tied to Publishing Target Not Updating
I am using the Publishing Service in a Sitecore 10.2 Production environment. We use deployment slots in Azure App Services. Each deployment slot has a dedicated Web database, Slot 1 has Web and Slot 2 has Web2.
The publishing targets in the publishing service are setup and I am able to publish to both. However, only the Slot 1 CD updates it content. The Slot 2 CD tied to Web2 only updates if I restart the Slot Web App.
On the 2nd Slot, I have my connectionString named as "web" just like the first slot but it's database entry for the connectionString is to the web2 database.
I suspect that the events of publishing are getting discarded/not read by the Slot 2 CD Web App.
How should I configure my 2nd Slot Web App so that it updates on publish without restarting the whole app?
My Sitecore.Publishing.Service.Delivery.config is the default that comes with the Publishing Service Module:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore role:require="Standalone or ContentDelivery or ContentManagement">
<hooks>
<hook type="Sitecore.Publishing.Service.Delivery.PublishTargetEventsHook, Sitecore.Publishing.Service.Delivery" resolve="true"/>
</hooks>
<!--
SITECORE EVENTS
-->
<events>
<event name="publishingservice:searchindex:rebuild">
<handler type="Sitecore.Publishing.Service.Delivery.TargetSearchIndexRebuildHandler, Sitecore.Publishing.Service.Delivery" method="RebuildTargetSearchIndex">
<IndexNames hint="list:AddIndex">
<index>sitecore_web_index</index>
</IndexNames>
</handler>
</event>
<event name="publishingservice:cache:clear">
<handler type="Sitecore.Publishing.Service.Delivery.TargetDataCacheClearHandler, Sitecore.Publishing.Service.Delivery" method="ClearTargetDataCaches" />
</event>
</events>
</sitecore>
</configuration>
Update: I have added a 2nd connectionString to my CD2 and the following configuration to use web2 (which properly applies website to be using web2), but the content is still not showing unless I restart the server (this could be either a CMS or the CD2 Web App restart).
Of note: In checking the Sitecore Desktop Content Editor, my publishing to Web shows all the content but but Web2 the Publishing Service says it has published, but items are not being updated/showing if you go into the Sitecore Desktop Content Editor for Web2 unless CMS/CD Web Apps are restarted to rebuild from the database.
<?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>
<eventing defaultProvider="sitecore">
<eventQueueProvider>
<eventQueue name="web2" patch:after="eventQueue[@name='web']" type="Sitecore.Data.Eventing.$(database)EventQueue, Sitecore.Kernel">
<param ref="dataApis/dataApi[@name='$(database)']" param1="$(name)" />
<param hint="" ref="PropertyStoreProvider/store[@name='$(name)']" />
</eventQueue>
</eventQueueProvider>
</eventing>
<PropertyStoreProvider>
<store name="web2" patch:after="store[@name='web']" prefix="web2" getValueWithoutPrefix="true" singleInstance="true" type="Sitecore.Data.Properties.$(database)PropertyStore, Sitecore.Kernel">
<param ref="dataApis/dataApi[@name='$(database)']" param1="$(name)" />
<param resolve="true" type="Sitecore.Abstractions.BaseEventManager, Sitecore.Kernel" />
<param resolve="true" type="Sitecore.Abstractions.BaseCacheManager, Sitecore.Kernel" />
</store>
</PropertyStoreProvider>
<databases>
<!-- web_secondary -->
<database id="web2" patch:after="database[@id='web']" singleInstance="true" type="Sitecore.Data.DefaultDatabase, Sitecore.Kernel">
<param desc="name">$(id)</param>
<icon>Images/database_web.png</icon>
<securityEnabled>true</securityEnabled>
<dataProviders hint="list:AddDataProvider">
<dataProvider type="Sitecore.Data.DataProviders.CompositeDataProvider, Sitecore.Kernel">
<param desc="readOnlyDataProviders" hint="list">
<protobufItems type="Sitecore.Data.DataProviders.ReadOnly.Protobuf.ProtobufDataProvider, Sitecore.Kernel">
<filePaths hint="list">
<filePath>$(dataFolder)/items/$(id)</filePath>
<modulesFilePath>/sitecore modules/items/$(id)</modulesFilePath>
</filePaths>
</protobufItems>
</param>
<param desc="headProvider">
<dataProvider ref="dataProviders/main" param1="$(id)">
<disableGroup>publishing</disableGroup>
<prefetch hint="raw:AddPrefetch">
<sc.include file="/App_Config/Prefetch/Common.config" />
<sc.include file="/App_Config/Prefetch/Webdb.config" />
</prefetch>
</dataProvider>
</param>
</dataProvider>
</dataProviders>
<PropertyStore ref="PropertyStoreProvider/store[@name='$(id)']" />
<remoteEvents.EventQueue>
<obj ref="eventing/eventQueueProvider/eventQueue[@name='$(id)']" />
</remoteEvents.EventQueue>
<archives hint="raw:AddArchive">
<archive name="archive" />
<archive name="recyclebin" />
</archives>
<cacheSizes hint="setting">
<data>100MB</data>
<items>50MB</items>
<paths>2500KB</paths>
<itempaths>50MB</itempaths>
<standardValues>2500KB</standardValues>
</cacheSizes>
</database>
</databases>
<sites>
<site name="website" set:database="web2" />
</sites>
</sitecore>
</configuration>
| |
We followed @marek-musielak's advice but had to expand it a bit.
We added the following Controller Factory:
public class ControllerFactory : SitecoreControllerFactory
{
public ControllerFactory(IControllerFactory innerFactory) : base(innerFactory) { }
public override IController CreateController(RequestContext requestContext, string controllerName)
{
try
{
return base.CreateController(requestContext, controllerName);
}
catch (ControllerCreationException)
{
return new DefaultController();
}
}
protected class DefaultController : Controller { }
}
And registered it using:
public class InitializeControllerFactory
{
private readonly Func<ControllerBuilder> _controllerBuilder = () => ControllerBuilder.Current;
public virtual void Process(PipelineArgs args) => SetControllerFactory(args);
protected virtual void SetControllerFactory(PipelineArgs args)
{
var controllerBuilder = _controllerBuilder();
SitecoreControllerFactory controllerFactory = new ControllerFactory(controllerBuilder.GetControllerFactory());
controllerBuilder.SetControllerFactory(controllerFactory);
}
}
Now our solution always returns 404 when no controllers are found.
|
HTTP 500 errors when accessing custom route which can't find a controller
Every time somebody tries to access a route "below" our custom API routes, we see an HTTP 500 error. Such errors are quite messy in our log, and we would like to convert it into 404 errors instead, but don't know how.
We have registered custom API routes through the following code:
public void Process(PipelineArgs args)
{
RouteTable.Routes.MapMvcAttributeRoutes();
RouteTable.Routes.MapRoute("airshoppen-api", "api/{controller}/{action}");
}
The routing works just fine when we access a controller which exists (e.g. /api/user/), but fails with an exception (and thereby a 500 error) when not (e.g. /api/nosuchcontroller).
The routes have been registered through the following pipeline:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<initialize>
<processor type="Website.Feature.Routing.Pipelines.RegisterApiRoutes, Website.Project.Common" patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />
</initialize>
</pipelines>
</sitecore>
</configuration>
Any tips on how to ensure that we don't get spammed with 500 errors?
Note: The error in our log is:
Sitecore.Mvc.Diagnostics.ControllerCreationException:
at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController (Sitecore.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null)
at System.Web.Mvc.MvcHandler.ProcessRequestInit (System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.Mvc.MvcHandler.BeginProcessRequest (System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.HttpApplication+CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.HttpApplication+<>c__DisplayClass285_0.<ExecuteStepImpl>b__0 (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.HttpApplication.ExecuteStepImpl (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.HttpApplication.ExecuteStep (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
Inner exception Sitecore.Mvc.Diagnostics.ExceptionWrapper handled at Sitecore.Mvc.Controllers.SitecoreControllerFactory.CreateController:
| |
This appears to be related to an incompatibility with SitecoreDockerTools and PowerShell 7.3. A colleague (Jason Bert) was able to get past this by running with PowerShell 5.1 (though I run into a separate issue there).
I was able to resolve this by using the "mkcert" utility as documented here:
https://doc.sitecore.com/xp/en/developers/100/developer-tools/run-your-first-sitecore-instance.html
mkcert -cert-file traefik\certs\xm1cm.localhost.crt -key-file traefik\certs\xm1cm.localhost.key "xm1cm.localhost"
for CM, CD, and ID roles.
Reported to Sitecore as a defect (CS0399761).
** When I tried to run compose-init.ps1 with PowerShell 5.1, I ran into this error:
> A parameter cannot be found that matches parameter name
'AllowPrerelease'.
So neither PowerShell 5.1 nor 7.3 runs cleanly.
|
Traefik cannot read private key error
I created a new XM1 developer environment using the official Container Deployment Package, using PowerShell 7.3.6 elevated. After running Compose-Init.ps1 and docker compose up -d, when trying to hit https://xm1cm.localhost I receive a certificate error, because the site is served using the Traefik Default Certificate, rather than the signed one created by the compose-init.ps1 process. Examining the Traefik logs shows this error:
level=error msg="Unable to append certificate -----BEGIN CERTIFICATE-----\r\n[key removed]\r\n-----END CERTIFICATE-----\r\n to store: unable to generate TLS certificate : tls: failed to parse private key" tlsStoreName=default
| |
Out of the box, Sitecore should be storing your files in the database rather than on the file system.
If this is not the case, then its likely that some config changes have been made.
Please try logging in to the sitecore back end, then going to:
/sitecore/admin/showconfig.aspx
Please check to see if the setting Media.UploadAsFiles is false and Media.DisableFileMedia is true.
If this is not the case, then you should look in your config files and see where this is set and try changing it to see if that works.
I believe with those settings switched over, the system will revert to storing as blobs. Then if you have enable the blob storage module correctly, it will push to storage instead of database.
More info here:
How to store media files in file system
|
Why media files are storing in file system in Sitecore 10.3.I enabled Azure blob storage?
I enabled blob storage using this article. What is the reason still files are stored on the file systems?
https://doc.sitecore.com/xp/en/developers/103/sitecore-experience-manager/enable-the-azure-blob-storage-module-for-sitecore-blobs.html
| |
If you have a sql management studio or something similar, please follow this steps.
First find your docker network by:
docker network ls
then find out the IP of the Sql server using the docker inspect, for example:
docker inspect [Your Network Name or ID]
docker inspect xmcloud_default
which will show you the internal IP of the SQL:
"93a5e82efb3a1ec6a14d91033564975d9b16c3eb82d8455e7141d35416f0233d": {
"Name": "xmcloud-cm-1",
"EndpointID": "49131e48c6ed7759b1e7a871b0979130c1cbb4bb504a2a26105d6679eaf606cb",
"MacAddress": "00:15:5d:a7:c5:07",
"IPv4Address": "172.29.158.178/16",
"IPv6Address": ""
},
"ee4b0eb869c7d5897372e6096ba22f0ac8bbb3805211932b5ead52ca9f4bf78d": {
"Name": "xmcloud-mssql-1",
"EndpointID": "8394fe5b5ecd2d56d3685202fd31c745c2df9e3bdd7ae801bec32aca940413df",
"MacAddress": "00:15:5d:a7:c4:29",
"IPv4Address": "172.29.154.34/16",
"IPv6Address": ""
}
Open the SQL management studio and connect to SQL using the ip (172.29.154.34). The username is sa and password is in your .env file variable SQL_SA_PASSWORD.
Find your user in aspnet_Membership table from Sitecore.Core database and set the IsLockedout to false.
|
Sitecore XM Cloud Error: User is locked out
I am using XMCloud on my local docker instance, but it locked my user after entering my cloud logins multiple times (by mistake). now when I am running my local URL to log into Sitecore it shows an error that the User is locked out. I can log into the cloud portal in all environments, but this is only on local. So far I tried multiple options including up and down the instance. Do we have any option to resolve the locked-out user or any alternative way to log in using an admin account?
| |
For this you need to write some custom code snippet which allows you to hide the field on the basis of your condition.
This is an example of code that you can follow and modify it as per your needs.
public void Process(GetContentEditorFieldsArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (args.Sections == null || args.Sections.Count == 0)
{
return;
}
this.Args = args;
if (this.Args.Item != null && this.Args.Item.Paths.FullPath.StartsWith("/sitecore/content", System.StringComparison.OrdinalIgnoreCase))
{
//Get Id of the different fields to hide. Example:
string excludedFields = "{AC2F70FF-F2C3-44AE-8F2E-6BFE44162DDC}";
if (!string.IsNullOrWhiteSpace(excludedFields))
{
//determine the template sections that needs to be hidden and remove that from the list
this.Args.Sections.RemoveAll(p => excludedFields.Contains(p.ID.ToString()));
//determine the fields that needs to be hidden and remove those from the content editor list
this.FilterFieldsFromSections(excludedFields);
}
}
}
private void FilterFieldsFromSections(string excludedFields)
{
if (this.Args.Sections != null && this.Args.Sections.Count == 0)
{
return;
}
for (int fieldIndex = 0; fieldIndex < this.Args.Sections.Count; fieldIndex++) { Editor.Section currentSection = this.Args.Sections[fieldIndex]; if (currentSection != null && currentSection.Fields != null) { currentSection.Fields.RemoveAll(p => p.ItemField != null && excludedFields.Contains(p.ItemField.ID.ToString()));
}
}
}
Then you will need to patch the pipeline getContentEditorFields in order to trigger the code
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<getContentEditorFields>
<processor type="YourNamespaceWithClassName, YourAssemblyName"/>
</getContentEditorFields>
</pipelines>
</sitecore>
</configuration>
Note that your pipeline needs to get triggered last else it will get overriden by Sitecore Pipeline getContentEditorFields
Ref: https://hishaamn.wordpress.com/2016/11/02/sitecore-hide-field-on-content-editor/
Hope this helps.
|
How to add restriction to a Template Field so that it ll show/hide based on selected language version
I just want to show a template field to content editor when Poland language version is selected for the item. and want to not show that field if Romania language is selected.
Can someone pls suggest how to do it.
| |
In the end, this turned out to be a problem of the traefik certificate.
The script docker/scripts/installCertificate.ps1 when executed with all permissions under the local user account in admin mode, had not thrown any error. But also not installed the certificate.
Solution was to log in on the laptop as an Administrator, run installCertificate.ps1 there. Then find the certificate in the certificate manager, export it, and import it to a trusted folder where the local user has access to.
It took a while to find out because Firefox needed to be restarted before it really tried to find the certificate again. A private window did not do the trick.
I hope this will save some time to other users.
|
Sitecore login redirects to http instead of https after we added 'hostname' attributes in docker-compose.yml
We are running sitecore with docker in version 10.1.2 (rev. 006578).
On the customers laptop, apparently due to the companies security policy, the docker containers could not communicate with each other. As a result, xconnect was unhealthy because it could not reach the container with the SQL Server.
Thanks to the solution provided here https://sitecore.stackexchange.com/a/26177/1425, we solved this by setting the hostname attribute in docker-compose.yml for all services, always repeating the container id, like here:
This was the only change. It solved the issue with the containers communicating to each other but when we try to log in to Sitecore, the redirects are broken now, because they redirect to http and not https protocols. For example when calling https://cm.mum.localhost/sitecore/admin, the redirect goes to:
The same in any step that follows. When we correct the addresses by adding the 'https://' in the browser's address bar, all works fine.
We checked sites.config and it looks fine:
Any idea how we can fix this?
| |
No, they are not deleted, not even orphan blobs. However, orphan blobs can be deleted from Sitecore XP:
(Control Panel => Administration tools => Database Cleanup => Database Name => Cleanup Blobs => Execute Cleanup)
For more details see the blog post: Sitecore Media in Database Vs. File Directory Vs. Blob Storage
What is the way to migrate existing media files that are stored in a
file system?
Yes, you use the blob migration tool to help migrate blobs from SQL Database to Azure Storage and vice-versa. Use the blob migration tool
|
Why Media file is not deleted automatically from blob storage in Sitecore 10.3 when I delete it from Sitecore?
I recently enabled Azure blob storage in Sitecore 10.3. If I delete a file from Sitecore, it is not deleted from blob storage. I deleted the item from Recycle Bin of Sitecore and I ran database blob cleanup as well.
| |
Solution for unlocking items locked by a specific user.
Get-ChildItem master:\content -rec -Language * |
Where-Object { $_.Locking.GetOwner() -eq "sitecore\USERNAME" } |
% { $_.Locking.Unlock() }
Unlock Item command button in Sitecore Content Editor. Allow access of this button to specific role only.
public class UnlockItem : Command
{
public override void Execute(CommandContext context)
{
if (context.Items.Length != 1)
return;
var item = context.Items[0];
if (item.Locking.IsLocked() && item.Access.CanWrite())
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
item.Locking.Unlock();
}
}
}
public override CommandState QueryState(CommandContext context)
{
if (context.Items.Length != 1)
return CommandState.Hidden;
var item = context.Items[0];
if (!item.Locking.IsLocked() || !item.Access.CanWrite())
return CommandState.Hidden;
return base.QueryState(context);
}
}
Patch config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<commands>
<command name="contenteditor:unlockitem" type="MyAssembly.Namespace.UnlockItem, MyAssembly" />
</commands>
</sitecore>
</configuration>
And add a new button in core database under: /sitecore/content/Applications/Content Editor/Ribbons/Chunks/Locks item
Credit: https://www.skillcore.net/sitecore/sitecore-unlock-item-command
Hope it helps!
|
What permissions needed to unlock items for a non-admin
We have a multi-lingual multisite instance with v10.1.3
And there are authoring roles for each site & role.
A common occurrence is, items are locked by a person who is unavailable and the current author does not have the option to unlock/check-in. So, an admin would unlock those items.
For some items, the admin can see the Elevated unlock option and for some, that option is not available. So admin has to do a Review > Check-in.
Is there a way to unlock items that are locked by a specific user, using powershell.
Is there any way to give the option to the author itself, without making them an admin, like adding any default or custom role
| |
SPE includes a toolbox item called "Transfer item security" which provides a way to query what's in the database matching a role or user and transfer ownership to a new role.
You can find the source code here if you are on a version of SPE prior to 6.4.
https://github.com/SitecorePowerShell/Console/blob/5c672b42b3a1859e36c82f426a10e053c8001608/unicorn/SPE/Scripts/SPE/SPE/Tools/Security%20Management/Toolbox/Security%20Management/Transfer%20item%20security.yml
https://github.com/SitecorePowerShell/Console/issues/975
|
How to merge two roles into one, and delete the two old ones?
We have an old Sitecore installation, and I need to clean up and consolidate our own created roles. We have partial overlapping roles and too many to make them useful. I prefer to do it with spe or C# and not directly in the db.
So to be more precise - how do I extract the rights to the items from each of the two roles and merge the two into one new role and delete the two old one’s?
| |
First of all, IIS Rewrite Rule will not know your template so
only for article and not for other templates
part cannot be achieved, unless you can specify the part of url which is only present before the article name, e.g. /article.
I'm not sure what you mean by "If it is having, we just need to replace that value with blank values" - I assume you want to remove both year and month from the url and redirect. In that case, you can use the following rule:
<rule name="article redirect" enabled="true" stopProcessing="true">
<match url="^(article)/[0-9]{4}/[0-9]{2}(.*)$" />
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}{R:2}" />
</rule>
|
How to replace YEAR and MONTH from URL using IIS rewrite rule?
We would like to check whether the particular URL request having the bucket structure. If it is having, we just need to replace that value with blank values and do the redirection (only for article and not for other templates).
/article/2023/04/pagename
/article/year/month/pagename
Do we have any option in IIS rewrite rule?
| |
I'm a .Net Backend developer too, I will share my experience in an XM Cloud project.
Definitely, you have to expand your knowledge and learn the basics of React and NextJS, hooks, and TypeScript to start working with the NextJs Starter you mentioned.
In my experience, a Frontend fellow gives me the HTML and all the styling, animations, and pretty CSS classes to make the user experience great, and we have to integrate in .tsx components that will be called in a JSON Rendering in the CMS, similar as we had before with View or Controller renderings.
As BE, if apply for your company's role, you still have to create the templates, renderings, placeholders, layouts, assign data sources, create APIs, create GraphQL queries, and of course, retrieve the data from the content items to our components.
On Github, there's the base branch of the Starter code with examples on how to work with components, here's the link:
https://github.com/sitecorelabs/xmcloud-foundation-head
And in my blog https://sitecoretek.wordpress.com/ you can find some posts that will help you and save time, for example, the initial setup of the project, working with placeholders, and work with GraphQL locally.
Hope this finds you helpful, and trust me, is a new very exciting world to work with XM Cloud and headless.
|
XM Cloud Sitecore Information BE
not needed, please delete it thanks . asdasdasdasdsadasdsadasd
| |
There is no OOTB field for DOB field in Sitecore form. You can have two options here.
If you install Sitecore Form Extension then you will get future date, past date and minimum age 18 validator with the package. As given in below image.
Refer to this link for more details.
Another option is to create custom validator to create a validation like this.
Refer to this Sitecore Document to know how to create a custom validator.
https://doc.sitecore.com/xp/en/developers/90/sitecore-experience-manager/walkthrough--creating-a-custom-validator-based-on-the-existing-regular-expression-validation.html
Hope this helps.
|
Date of Birth field for Sitecore Forms
I have requirement to add DOB field in Sitecore Forms in version 10.0.
Is there any OOTB field that can be used for this.
I see Date field is there but it is allowing current/future date selection also.
Kindly suggest what can be best OOTB option here.
| |
This is how you can try to get the value of two fields of the same name. This is my item.
And this is the script
$item = Get-Item master:\content\home\new
Get-Item -Path "master:" -Query "/sitecore/content/home/new" |
Show-ListView -property "Title", @{Label="Title2"; Expression={$_.Fields["{76D4FC9B-ADC1-496E-AB3A-0264679D65A2}"].Value}}
In the above query for Title2 label, I have given the field ID of the same field name.
And it will give me results like this.
Hope this helps.
|
Get value of field with same name using Sitecore powershell
There are two fields with the same name Title in a Sitecore item, Is there a way to get the values of both fields using Sitecore PowerShell?
| |
Sitecore tokens are used to populate field value and not field names. You should define field names before creating items from it and use sections to keep related fields together.
Fields are like properties in a template, you can't make it dynamic. It is not at all advisable to change field names at the time of item creation.
|
Custom token to rename Fields in Template
How can we create custom token in Sitecore to rename the fields of the template items at the time of item creation ?
I want my fields to be renamed similar to general link fields present on the template.
Example - If I have general link field named Learn more and I want to create a token which will rename the field as LearnMoreGTM link.
I want to do it for at least 4 fields as its the maximum number of general link field we have in our project.
Any thoughts ?
| |
It's because of the differences in the Windows version.
For that, we need to update the below parameters in the .env file,
SITECORE_VERSION=10.3-ltsc2019 -- line no 3
EXTERNAL_IMAGE_TAG_SUFFIX=ltsc2019 -- line no 36
And re-run the docker-compose command.
Check out the below links for checking the compatible version for your Windows machine.
https://hub.docker.com/_/microsoft-windows-nanoserver
|
Getting an error while running the docker-compose command - "a Windows version 10.0.20348-based image is incompatible with a 10.0.19044 host"
I am trying to install Sitecore 10.3 with Docker. While running docker-compose command I have encountered below issue.
The error message I get is:
a Windows version 10.0.20348-based image is incompatible with a 10.0.19044 host
Has anyone faced this?
| |
Im wondering if it is something to do with the way you are enabling/disabling identityserver?
Assuming you are using code similar to the below to log the virtual user:
User virtualUser = Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser("extranet\\[email protected]", true);
Sitecore.Security.Authentication.AuthenticationManager.LoginVirtualUser(virtualUser);
Instead, please can you try a slighty different approach
YourConstructor(ProviderHelper<AuthenticationProvider, AuthenticationProviderCollection> providerHelper)
{
User virtualUser = providerHelper.Provider.BuildVirtualUser("extranet\\[email protected]", true);
}
Note: if you decompile the sitecore.kernel dll, you can see that a similar thing is happening when you call Sitecore.Security.Authentication.AuthenticationManager. First of all, it checks to see which dependency is registered for BaseAuthenticationManager (which is DefaultAuthenticationManager). That class accesses the dependency shown above in the same way to get a providerHelper, and from that selects the default Provider (which in this case is Forms I believe).
If you then put a break point in the code and inspect what the provider is in both cases (which should be 'Forms'). Im wondering if the config you are applying is disabling this somehow when enabling identity server?
I just tried logging in a virtual user, using the approach shown here: https://www.kasaku.co.uk/2017/11/22/virtual-user-custom-properties/
Both with and without identity server enabled, I was able to see the virtual user shown as the Sitecore.Context.User on subsequent calls.
|
Unable to login virtual user from sitecore when identity server is enabled
I am setting up sitecore identity server to pass through authentication to Okta for some of our portals. However some of our portals already have a manual authentication approach taken which logs in the virtual user using the AuthenticationManager. When I enable Sitecore Identity server this code fails when trying to login the virtual user.
Is there something I can do to workaround this issue or do I need to change these over to be handled by the identity server?
My guess is that Sitecore now wants the identity server to authenticate the user and will not do it internally any more.
Any help is appreciated.
UPDATE:
If I use the following instead:
var providerHelper = Sitecore.DependencyInjection.ServiceLocator.GetRequiredResetableService<ProviderHelper<AuthenticationProvider, AuthenticationProviderCollection>>();
var user = providerHelper.Value.Provider.BuildVirtualUser(username, true);
The code seems to work but then fails at a later unrelated section of code. No idea why this is happening, any suggestions would be appreciated.
Below is the code we are running to login in the user (I have removed a lot of the boilerplate). It is running in a custom sitecore pipeline
<processor type="MLCGP.Security.Feature.Pipelines.OAuthSignInCallback,MLCGP.Security.Feature" patch:before="processor[@type='Sitecore.Pipelines.HttpRequest.UserResolver, Sitecore.Kernel']" >
namespace MLCGP.Security.Feature.Pipelines
{
public class OAuthSignInCallback : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
var idToken = args.HttpContext.Request.Form["id_token"];
LoggedInUserInfo claims = null;
try
{
log.Debug($"calling ValidateOpenIdIdentityToken for domain '{Settings.MemberDomain}'", this);
// Validate token and construct claims prinicpal / session security token
claims = oktaService.ValidateOpenIdIdentityToken(idToken, Settings.MemberDomain);
}
var user = UserHelper.CreateMemberUser(claims);
}
}
}
public static User CreateMemberUser(LoggedInUserInfo loggedInUserInfo)
{
var claimsProcessor = new OpenIdClaimsMapper();
var userClaims = claimsProcessor.Map(loggedInUserInfo);
var username = loggedInUserInfo.UserName;
var providerHelper = Sitecore.DependencyInjection.ServiceLocator.GetRequiredResetableService<ProviderHelper<AuthenticationProvider, AuthenticationProviderCollection>>();
//var user = AuthenticationManager.BuildVirtualUser(username, true);
var user = providerHelper.Value.Provider.BuildVirtualUser(username, true);
AssignUserRoles(user, userClaims, loggedInUserInfo.Domain);
providerHelper.Value.Provider.LoginVirtualuser(user);
//AuthenticationManager.LoginVirtualUser(user);
return user;
}
| |
Incase you are not using a custom Sitecore Form submit action and if you suspect jQuery conflict is happening somewhere, its worth to have a look at your scripts loading from Themes folder(If you are using SXA)
Detailed answer - Sitecore Forms on Submit: Cannot read property 'unobtrusive' of undefined
Hope it helps!
|
Uncaught TypeError: Cannot read properties of undefined (reading 'unobtrusive')
I am getting an error below while submitting the Sitecore forms in the Sitecore 10.3 version.
Uncaught TypeError: Cannot read properties of undefined (reading 'unobtrusive')
Does anyone ever encounter this issue? any help is appreciated.
| |
If you are a developer and wish to contribute, then you should have access to source control (Github, AzDo etc. wherever you are managing your code).
You can have containerized setup locally that would host your Sitecore part. Your code repository (Front end + Back end - considering headless implementation) should be cloned locally and your changes should be deployed and verified on your local containers.
Content changes are managed through Serialization (Sitecore Content Serialization mostly). Content changes like Templates, Layouts, Renderings etc. should be maintained in Source code along with your code files.
Deployment Pipelines will deploy your changes to Upper Environment. Each environment will have following pipelines -
Backend changes will be deployed to Sitecore XM Cloud environment.
If you have headless implementation then you will have a separate deployment process for front end application as well (Ex. - Vercel in case of NextJs)
This will be needed for each environment and may vary as per your architectural setup.
Roughly it would look like this (This is not a recommendation, number of environments may vary, few more service components may exist which are not shown here) -
I hope this clears the flow.
|
Pull Sitecore Project
TBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBDTBD
| |
Sitecore Forms is not available in XM Cloud yet, but Sitecore are planning to provide a XM Cloud Forms by the end of 2023. Currently you would need to use an 3rd party form provider such a Jotforms or Marketo.
I don't think Sitecore Data Exchange is available in XM Cloud either as it uses Pipelines and there are no CD servers in XM Cloud for Pipelines to run on, it's possible it would run on the CM but I imagine it's not installed and you can't install modules in XM Cloud.
Also re some of your other points:
Experience Analytics & Personalization - are A Light version of Sitecore Personalize & Sitecore CDP is included in XM Cloud which means some personalisation and basic web analytics and page performance metrics are available.
Horizon - this is replaced with Pages (which essentially was built from Horizon) and it has more features than Horizon did including a components builder.
I presented and wrote an blog post about XM Cloud here which you might find useful: https://www.flux-digital.com/blog/xm-cloud-demystified/
|
Differences between Sitecore XP and Sitecore XM Cloud
In our project, we are deciding whether we can move from XP to XM Cloud (SaaS) and need to understand the Impact of this, as far as I understand that the below features are not existing by default in SaaS:
Email Experience Manager
Marketing Automation
Campaigns
Experience Analytics
Horizon
Personalization
however I am not sure if Sitecore Forms and Sitecore Data Exchange are available in SaaS version or not.
Please advise.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.