Tuesday, December 3, 2024

Handling Special Characters in Sitecore Search: Current Limitations and Challenges

I recently contacted Sitecore Support to explore whether it’s possible to configure search functionality to better handle queries containing only special characters. Specifically, I wanted to ensure that such queries return no results without requiring front-end adjustments or UI-level changes.

Current Search Behavior

At present, Sitecore’s search system does not manage this scenario effectively. When a search query consists solely of special characters, the platform doesn’t filter them out and ends up returning all results. While Sitecore's search analyzer uses a predefined list of stop words to exclude common terms, there is no equivalent mechanism to handle special characters.

Sitecore’s Response

After a detailed review, Sitecore Support confirmed that there is no built-in functionality to address this issue. Filtering out queries with only special characters is not supported out-of-the-box and would require custom development or alternative workarounds beyond Sitecore's default capabilities.

Next Steps and Considerations

Given the lack of a native solution, I have opted to close the support ticket for now. However, this is an area where Sitecore could consider future enhancements to improve search accuracy and behavior.

In the meantime, teams facing similar challenges may need to explore custom implementations or front-end validation to handle such search queries effectively.

Thursday, November 14, 2024

Pages Rich Text Editor (RTE) Lacks Internal Sitecore Link Functionality

While working with the Rich Text Editor (RTE) in Pages, we noticed a limitation: it doesn’t allow the creation of internal Sitecore links. This makes it harder for the marketing team to seamlessly add internal links directly within the Pages interface, disrupting their workflow and efficiency.

Current Status

Sitecore Support has confirmed that this functionality is not currently available in the Pages RTE.

  • A feature request (PGS-1236) has been created for consideration in future releases.
  • In the meantime, the recommended workaround is to add internal links directly through the Content Editor.

Workaround

For now, internal links can be added by:

  1. Navigating to the Content Editor.
  2. Editing the Rich Text field and manually inserting internal links.

Next Steps

  • Monitor the status of the feature request (PGS-1236) via the Sitecore Support portal.
  • Consider educating content authors on the temporary workaround until the feature is available in Pages.

We hope to see this functionality in upcoming releases to streamline the authoring experience for internal linking directly in Pages.

Wednesday, November 13, 2024

Custom Class Not Retained in Rich Text Editor (RTE) in Page Editor Mode (XMCloud)

In Sitecore XM Cloud's Page Editor, the Rich Text Editor (RTE) has an issue where custom class attributes applied to HTML elements, such as a <span>, are not preserved. After saving and reopening the RTE, these elements are automatically converted to <p> tags, causing the custom class to be stripped away.

Example:

Input:


<span class="small-text">Sample Text</span>

After saving and reopening:


<p>Sample Text</p>

Investigation and Findings

  • The issue occurs exclusively in Pages' RTE, which uses Quill.js as the editor.
  • In the Content Editor's RTE, custom attributes like <span> and class are preserved as expected.
  • This behavior is linked to Quill's optimization process, which standardizes and simplifies HTML during editing.

Recommended Resolution

To address this issue, Sitecore Support recommends switching to the latest CKEditor RTE, which resolves the problem and supports retaining custom attributes like classes.

Steps to Enable CKEditor in Sitecore XM Cloud

  1. Update Configuration:

    • Replace Quill.js with CKEditor as the default Rich Text Editor for the Page Editor.
  2. Validate Custom HTML:

    • Ensure that CKEditor preserves custom HTML elements and attributes in your environment.
  3. Test and Deploy:

    • Test the new RTE configuration thoroughly in a staging environment before rolling it out to production.

For detailed instructions, refer to the official Sitecore documentation: Enabling CKEditor in Sitecore XM Cloud.

Workaround

If switching to CKEditor is not immediately feasible, you can manage custom HTML via the Content Editor RTE, where the issue does not occur.

Outcome

By implementing CKEditor, you can retain custom classes and resolve this limitation in the Page Editor's RTE, ensuring better flexibility and alignment with custom styling requirements.

Tuesday, November 12, 2024

Sitecore API Pagination and Sorting Errors

The Sitecore API was experiencing critical issues impacting pagination and sorting functionalities. Whenever users attempted to navigate to subsequent pages or apply sorting, the API returned internal server errors (500), rendering the features unusable.



Issue Summary

  1. Internal Server Errors (500):
    When pagination or sorting requests were sent, the API intermittently responded with:



    { "widgets": [ { "rfk_id": "test_widget_1", "type": "content_grid", "errors": [ { "message": "Internal Server Error", "code": 1001, "type": "internal_server_error", "severity": "HIGH" } ] } ] }
  2. Sorting Failures:
    Sorting configurations such as title_asc_asc or title_desc_desc failed to produce expected results. Responses either returned incorrect data or triggered the same server error.

  3. Inconsistent Pagination Behavior:
    For example, attempting to navigate to page 2 through /search?page=2 consistently produced the following:


    { "message": "Internal Server Error", "code": 1001, "type": "internal_server_error" }

Root Cause (Identified by Sitecore Team)

The Sitecore support team determined that the issue was caused by:

  1. A combination of boost rules and pagination settings that conflicted under certain API configurations.
  2. Faulty API handling logic when fetching large datasets while applying custom sorting and pagination rules.

Resolution

  1. System Update:
    Sitecore implemented a patch to rectify how boost rules interact with pagination requests.
  2. Configuration Adjustments:
    The team updated internal settings to ensure sorting worked seamlessly with pagination.
  3. Verification:
    After the fix was deployed, multiple test cases were executed to confirm that:
    • Pagination worked correctly.
    • Sorting options applied accurately without triggering server errors.

Wednesday, October 16, 2024

Indexing Shared Data Items from Search Result Pages in Sitecore

We ran into an issue while trying to index shared data items—like individual cards from a listing page—as separate items in Sitecore Search. Despite the extractor logic appearing correct, some of these items simply weren’t getting indexed.

Scenario

  • The search result page lists shared data items (not individual pages, so they don’t have distinct URLs).
  • The goal is to index each card on the page as an independent item in Sitecore Search with additional tags and logic for extra data values.
  • A flag was added to bypass the "Load More" functionality (?showAll=true) to make all cards visible on a single page for indexing.

Extractor Code

Here’s the extractor being used:


function extract(request, response) { const $ = response.body; const results = []; if (request.url.includes('image-gallery')) { $('div.row.layout').each((i, row) => { $(row).find('div.col-12.column.col-lg-4[gallery-layout="true"]').each((j, col) => { const dataAnchorTitle = $(col).attr('data-anchor-title'); const imgSrc = $(col).find('div.gallery figure img').attr('src'); if (dataAnchorTitle && imgSrc) { results.push({ title: dataAnchorTitle, image: imgSrc, type: 'gallery' }); } }); }); } return results; }

Issues Observed

  1. Only One Item Indexed: Despite having multiple items on the page, only one item is being indexed.
  2. Mandatory Fields: Missing mandatory fields in the index configuration could cause items to fail indexing.
  3. Order of Extractors: The sequence of extractors (JavaScript extractor vs. XPath extractor) might be causing conflicts.
  4. ID Generation: The ID for items was not being generated consistently, leading to indexing failures.

Resolution Steps

  1. Validate Extractor Logic:

    • Ensure the extractor captures all items on the page.
    • Hardcode mandatory fields temporarily to check if items get indexed correctly.
  2. Adjust Extractor Sequence:

    • Reorder the JavaScript Document Extractor to run before other extractors (e.g., XPath extractor) or remove unnecessary extractors.
  3. Generate IDs Programmatically:

    • Add logic to generate unique IDs for each item in the JavaScript extractor:

      const id = `${dataAnchorTitle}-${i}-${j}`; results.push({ id, title: dataAnchorTitle, image: imgSrc, type: 'gallery' });
  4. Re-Index and Validate:

    • Re-index with only the relevant extractor and verify results.
  5. Address Errors:

    • If errors like "heartbeat error" occur, retry indexing after resolving underlying connectivity or configuration issues.

Outcome

After implementing these changes:

  • All cards on the page were indexed as independent items.
  • Proper field mappings and unique ID generation ensured data integrity.
  • The reordering of extractors resolved conflicts during the indexing process.

These steps should help streamline indexing shared data items from listing pages in Sitecore Search.

Page Editor Doesn’t Show Current or Shared Site Name in Data Source

While working with the Page Editor, we noticed an inconsistency in how data source information is displayed compared to the Content Editor. In the Content Editor, data sources clearly indicate whether they belong to the "Current site" or a "Shared site." For example:

  • Carousels (Current site)
  • Carousels (Shared: Shared)
  • Media carousel 1
  • Data (Current site)

However, in the Page Editor, the same data sources are displayed without this distinction:

  • Carousels
  • Carousels
  • Media carousel 1
  • Data

This lack of clarity makes it challenging to differentiate between site-specific and shared data sources within the Page Editor.

Update from Sitecore

Sitecore Support confirmed that the Page Editor currently does not display the "Current site" or "Shared site" labels in the data source selection dialog, unlike the Content Editor.

To address this, Sitecore has created a Feature Request (PGS-2562) to enhance the Page Editor with similar functionality in a future update.

Next Steps

While we wait for the feature to be implemented:

  1. Cross-Verify in Content Editor: Use the Content Editor to confirm the origin of data sources until this feature is available in the Page Editor.
  2. Track Updates: Monitor the progress of the feature request (PGS-2562) with Sitecore Support.

This improvement will bring much-needed clarity and consistency to the Page Editor, simplifying workflows for content editors.

Tuesday, October 15, 2024

Persistent "Heartbeat Error" in Sitecore Search Indexing Jobs

We’ve been encountering a recurring issue during Sitecore search indexing jobs where they fail with the error: "Job failed due to heartbeat error." This error disrupts indexing and impacts production, creating a significant bottleneck in search functionality.



Key Observations

  1. Threshold Limitation:

    • The issue often relates to a threshold where if more than 30% of documents fail (e.g., due to 404 errors), the entire indexing job is discarded.
    • This threshold was confirmed by Sitecore Support as a hard limit with no current configuration option to adjust it.
  2. Unclear Error Reporting:

    • Errors like the "heartbeat error" provide no detailed context, making it difficult to determine whether the issue is due to resource limitations, 404 errors, or other failures.
  3. Sitemap Issues:

    • Delayed sitemap refreshes sometimes lead to invalid or outdated URLs being crawled, resulting in multiple 404 errors.
  4. Random Behavior:

    • In some cases, even with valid configurations and no 404s, jobs fail due to the heartbeat error without any clear cause.

Temporary Fixes Applied

  1. Adjusting Sitemap:

    • Updated and validated the sitemap to ensure all links are functional and up to date.
    • Excluded problematic URLs and broken links to reduce 404 errors.
  2. Simplified Extractor Configuration:

    • Removed unnecessary extractors to streamline the indexing process.
    • Combined document extractors to manage resources more efficiently.
  3. Retry Mechanism:

    • Reran jobs after addressing sitemap and threshold-related issues, which resolved some occurrences of the error.

Discussed below pionts with the Sitecore Team

During our investigation and resolution efforts for the persistent "heartbeat error," we requested the Sitecore team to address the following critical questions:

  1. Can the 30% Threshold Be Adjusted?

    • The current threshold causes the entire indexing job to fail if more than 30% of documents encounter issues (e.g., 404 errors). We inquired whether this threshold is configurable to accommodate different scenarios and prevent unnecessary failures.
  2. Improved Error Reporting:

    • We requested more descriptive error messages to clearly identify the root cause of failures, such as whether the issue is due to the 30% threshold, resource capacity, or another specific reason.
  3. Clarification on Heartbeat Error:

    • We asked whether the heartbeat error is solely tied to the threshold or if other factors, such as resource limitations or system configurations, could contribute to this issue.
  4. Sitemap Handling:

    • Given the potential delays in sitemap refreshes, we asked if there are recommendations for ensuring the crawler processes the most up-to-date sitemap without being affected by temporary 404 errors.
  5. Proactive Notifications:

    • We raised the need for proactive notifications for global incidents affecting crawlers, such as the ones reported in the Sitecore Status portal, to minimize downtime and ensure teams are informed promptly.
  6. Future Roadmap for Improvements:

    • We requested insights into Sitecore's plans for enhancing the search platform, including:
      • Allowing configurable thresholds.
      • Improving error handling and reporting.
      • Addressing known bugs or feature requests related to crawlers and extractors.

Wednesday, September 11, 2024

System Errors and Inconsistent Behavior in Search Platform


We recently faced significant disruptions with the Sitecore search platform. The errors were severe enough to impact our production environment, bringing development and delivery processes to a complete standstill. This was more than a minor glitch — it was a major roadblock.

The Root Cause

After investigating the issue, the Sitecore support team identified the culprit: an internal deduplication flag designed for Commerce Domains. This flag was mistakenly affecting search domains, leading to unexpected system errors and erratic behavior within the search platform.

The Resolution

To address this, Sitecore modified their logic to ensure that the deduplication flag no longer interferes with search domain functionality. Once the updated logic was deployed, they tested it thoroughly and confirmed the solution worked as expected in the production environment.

The Outcome

With the fix in place, all errors disappeared, and the search platform returned to normal operation. Sitecore has assured us that this update is a permanent solution, eliminating the risk of encountering the same issue in the future.

This experience highlighted the importance of thorough diagnostics and timely support, and we’re glad to see Sitecore taking swift action to resolve such critical issues. The platform is now stable, and we can continue development with confidence.

Friday, August 23, 2024

In Sitecore XM Cloud, sharing a site across multiple headless tenants isn't supported out-of-the-box due to the isolated nature of tenants. However, there are a few alternatives depending on your specific requirements:

Key Points

  1. SXA Shared Site:

    • SXA’s Shared Site feature allows sharing of presentation and data sources within a single tenant.
    • It does not support sharing across tenants by design, as tenants are meant to be isolated.
  2. Restructuring the Tenant/Site Setup:

    • If sharing site content across brands is essential, consider restructuring your tenant and site setup to group related sites under a single tenant.
    • Example:
      • Tenant (Brand):
        • Site 1 (Microsoft)
        • Site 2 (Apple)
  3. Item Cloning:

    • For specific content sharing, you can use the item cloning feature to replicate content across sites within a tenant.
    • This approach works well for small-scale content sharing.
  4. Role-Based Access:

    • Within a single tenant, you can create shared folders/sites and assign specific roles to users for access control.

Proposed Structure Example

  • Tenant A (Shared Site X):

    • Site 1
    • Site 2
    • Shared Site X
  • Tenant B (Shared Sites X and Y):

    • Site 3
    • Site 4
    • Shared Site Y
  • Tenant C (Shared Sites X, Y, and Z):

    • Site 5
    • Site 6
    • Shared Site Z

Recommendations

  • If restructuring tenants isn’t feasible, use item cloning or shared folders within a single tenant.
  • For better long-term scalability and fewer manual steps, align the tenant/site structure with the requirements for content sharing at the planning stage.
  • If sharing is minimal, item cloning may suffice without extensive rework.

This approach should help address your team’s need for shared sites across brands while adhering to Sitecore XM Cloud’s design principles.


Wednesday, August 14, 2024

Sitecore XM Cloud: Custom Error Details in Content Editor (YSOD)



Sometimes, when using the Sitecore XM Cloud Content Editor, you might encounter the Yellow Screen of Death (YSOD). This raises a common question: Can we enable custom error details to see more information about these errors?

The answer lies in modifying the web.config file. In XM Cloud, while you can adjust settings using XDT transformations, Sitecore doesn’t provide a direct option to enable custom error details specifically for the Content Editor.

To make changes:

  1. Check out the Sitecore documentation on XM Cloud build configuration.
  2. Use XDT transformations to adjust the relevant settings in the web.config file for your instance.

This should allow you to customize error handling and potentially show more details during troubleshooting.

Step-by-Step Approach to Enabling Custom Error Details

  1. Understand XM Cloud Deployment Model:
    Sitecore XM Cloud is a containerized environment, and configuration changes are handled through XDT transformations applied during the build process. You cannot directly edit the web.config in the deployed environment, but you can apply transformations during deployment.

  2. Modify web.config Settings:
    To display detailed error information, update the web.config settings using an XDT transformation to include custom error configurations.

    Here’s an example of an XDT transformation snippet you can use:


    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <system.web> <customErrors mode="Off" xdt:Transform="SetAttributes" xdt:Locator="Match(mode)" /> </system.web> <system.webServer> <httpErrors errorMode="Detailed" xdt:Transform="SetAttributes" xdt:Locator="Match(errorMode)" /> </system.webServer> </configuration>
    • customErrors mode="Off": Disables custom error pages and displays detailed ASP.NET errors.
    • httpErrors errorMode="Detailed": Configures the IIS server to display detailed error messages.
  3. Apply XDT Transformations in Your Build Configuration:

    • Ensure the above transformation file (e.g., web.release.config) is included in your project.
    • During deployment, Sitecore XM Cloud will apply this transformation to the web.config.
  4. Check Sitecore Documentation:
    Refer to the official Sitecore XM Cloud documentation on build configuration for guidelines on applying and validating XDT transformations in XM Cloud deployments.

  5. Deploy and Test:

    • Deploy the updated configuration to your XM Cloud instance.
    • Trigger the error in the Content Editor to confirm that detailed error messages are now displayed.

Best Practices and Considerations

  • Security Awareness:
    Only enable detailed error messages in non-production environments. Exposing detailed errors in a production environment can reveal sensitive information and pose security risks.

  • Log Monitoring:
    Use Sitecore’s logging mechanisms and external monitoring tools (such as Application Insights) to collect and analyze error data without displaying it directly in the Content Editor.

  • Rollback Strategy:
    Ensure you have a rollback plan in case the configuration changes cause unintended behavior.

Conclusion

While Sitecore XM Cloud does not offer a direct option to enable custom error details for the Content Editor, leveraging XDT transformations to modify the web.config file provides a powerful way to manage error handling. By applying these changes responsibly, you can streamline troubleshooting and improve the development experience.

For more detailed guidance, always refer to the official Sitecore documentation or reach out to Sitecore Support for assistance.

Friday, July 26, 2024

GraphQL Not Working for "Load More" Functionality on Published Environment


Issue: GraphQL Not Working for "Load More" Functionality on Published Environment

Summary:
The "Load More" functionality using GraphQL queries works correctly in preview mode and local environments but fails on the published GraphQL endpoint. The error message indicates an execution issue with the children query, specifically with the endCursor value.

Root Cause:

  1. Incorrect Context ID: The published environment may be using the Preview Context ID instead of the Live Context ID in the configuration.
  2. Unpublished Items: Items referenced in the query might not be published or available in the Live Experience Edge.
  3. Incorrect Cursor Value: The endCursor value may not be valid for the published environment, potentially copied from the Preview environment.

Solution:

  1. Update Context ID:

    • Set the correct SITECORE_EDGE_CONTEXT_ID for the Live environment in your hosting provider's environment variables (e.g., Vercel).
    • Redeploy the application to ensure the correct configuration.
  2. Verify Published Items:

    • Confirm that all required items are published and available in the Live Edge endpoint.
  3. Use Correct Cursor:

    • Run the initial query (children (first: 4)) without the after parameter on the Live endpoint to retrieve the correct endCursor value.
    • Use the returned endCursor for subsequent queries.
  4. Test Queries in Published Environment:

    • Verify the GraphQL query directly in the published GraphQL IDE to ensure the configuration works correctly.

By following these steps, the "Load More" functionality should work as expected in the published environment.

Thursday, July 25, 2024

Content Serialization Challenges in Sitecore XM Cloud


We encountered a recurring issue with content serialization in Sitecore XM Cloud, particularly when dealing with presentation updates like page branches and component renderings. Below is a summary of the problem, possible causes, and steps to replicate the issue.

Issue Description

  • Content changes, such as updates to page branches or component renderings, are serialized into .yml files and deployed to XM Cloud.
  • On the initial deployment, the updates reflect correctly in XM Cloud.
  • However, after subsequent deployments (even with unrelated changes), the previously deployed content reverts to its earlier state.
  • This behavior is observed only for certain renderings and not universally.

Suspected Cause

This behavior appears related to the interaction between:

  1. IAR (Items as Resources): Serialized content deployed as IAR files in XM Cloud.
  2. SQL Database in XM Cloud CM: Changes made directly in XM Cloud CM's content editor are stored in its SQL database, superseding IAR content.
  3. Deployment Overrides: Subsequent deployments fail to update content because the local serialized content doesn't reflect changes made in the XM Cloud CM.

Steps to Replicate

  1. Create a New Site:

    • Navigate to Presentation > Page Branches.
    • Create a new page branch template and add a component with rendering.
    • Update the component's data source and modify a value.
  2. Deploy Changes:

    • Serialize and deploy the changes to XM Cloud. Confirm that the changes are reflected.
  3. Perform Subsequent Deployment:

    • Make additional changes unrelated to the previous deployment.
    • Deploy again and observe that the earlier updates to the page branch or rendering have reverted.

Proposed Solutions

  1. Manual Cleanup:

    • Use the dotnet sitecore itemres cleanup --force command to remove outdated content in XM Cloud CM before deploying new serialized content.
  2. Synchronization:

    • Before deploying new serialized content, pull the latest content changes from XM Cloud CM to the local environment to ensure alignment between local and XM Cloud states.
  3. Direct Content Management:

    • If frequent authoring occurs in XM Cloud CM, coordinate deployments to minimize conflicts between serialized content and database-stored updates.

Best Practices

  • Track Content Changes: Maintain clear documentation of changes made in XM Cloud CM to prevent inadvertent overrides during deployments.
  • Test Locally: Validate serialized content thoroughly in local environments before deploying.
  • Streamline Collaboration: Establish workflows that synchronize content updates between developers and content authors effectively.

This approach should help mitigate inconsistencies in content serialization and deployment within Sitecore XM Cloud environments.

Wednesday, July 10, 2024

Resolving Facet Functionality Issues in Search Integration with Sitecore XM Cloud

During the integration of the Search application with Sitecore XM Cloud, we encountered an issue where facets functionality was not working as expected. While search results displayed correctly, the facets' checkboxes were unresponsive, and an error appeared in the console when attempting to interact with them.

Here’s a detailed breakdown of the problem and the steps taken to resolve it.

Issue Overview

  • Symptoms:
    • Facet checkboxes were displayed but were unresponsive to clicks.
    • Console error: Cannot read properties of undefined (reading 'facets').
  • Environment:
  • Observation:
    • The facets functionality worked perfectly during a proof of concept (POC) outside the XM Cloud environment with the same API and codebase.

Investigation

  1. Code Review:

    • The issue was identified in the SearchResultWidget.tsx component, particularly in the onFacetValueClick function.
    • An arrow function (onFacetValueClick={() => onFacetClick}) was used instead of directly passing the callback function.
  2. Environment Consistency:

    • Verified that the API response was identical in both environments (POC and XM Cloud).
    • Compared configurations and ensured the same codebase was deployed.
  3. Styled vs. CSS Components:

    • The demo site used styled components, whereas the integrated application used .css files. An attempt was made to replicate the behavior using styled components for troubleshooting.

Solution

  1. Fixing the Facet Click Logic:

    • Replaced the arrow function with a direct callback function.


    <SearchResultsAccordionFacets defaultFacetTypesExpandedList={[]} onFacetValueClick={onFacetClick} className="sitecore-accordion-facets-root" />
  2. Testing and Validation:

    • Updated the @sitecore-search/react package to version 2.2.3, resolving known bugs in earlier versions (2.1.1).
    • Validated the changes locally and deployed them to the XM Cloud environment.
  3. Facet Behavior in URL:

    • For modifying the facet behavior in the URL (displaying facet value instead of ID), implemented the useSearchResultsSelectedFacets hook from the Search SDK.

Key Findings

  • The issue originated from a combination of incorrect function usage and a known bug in the older version of the @sitecore-search/react package.
  • XM Cloud-specific configurations did not impact the functionality; the error was resolved by addressing code-level issues and updating dependencies.

Conclusion

By fixing the callback logic and updating the relevant package, the facets functionality was restored. This experience highlighted the importance of:

  1. Keeping dependencies up to date.
  2. Ensuring code consistency across environments.
  3. Validating functionality with minimal, reproducible examples.

If you encounter a similar issue, check your package versions, verify API responses, and thoroughly review component implementations. The above steps should help resolve most facet-related issues during Sitecore Search integrations.

Thursday, June 13, 2024

Option to Rollback Deployments in Sitecore XM Cloud

During a recent discussion with the Sitecore Support Team, we confirmed that XM Cloud does not offer a built-in rollback mechanism for deployments. However, since XM Cloud projects are typically hosted on version control platforms like GitHub, reverting changes can be managed effectively through version control processes.

uring a recent discussion with the Sitecore Support Team, we confirmed that XM Cloud does not offer a built-in rollback mechanism for deployments. However, since XM Cloud projects are typically hosted on version control platforms like GitHub, reverting changes can be managed effectively through version control processes.

Here’s a professional approach to handling rollbacks in XM Cloud using a Windows environment:

Step-by-Step Rollback Process

1. Revert Changes in Version Control

  1. Navigate to Your GitHub Repository (or any equivalent version control platform).
  2. Identify the Commit to Revert To:
    • Go to the Commit History of your repository.
    • Locate the last known stable commit before the problematic deployment.
  3. Revert the Commit:
    • On GitHub, click on the commit you want to revert.
    • Select the “Revert” option. This will create a new commit that undoes the changes introduced by the problematic deployment.
  4. Commit the Reverted Changes:
    • Confirm and commit the changes to your repository.

2. Link to a Stable Branch

  1. Create a New Branch for the Reverted Changes:
    • In GitHub, navigate to the repository’s Branches tab.
    • Create a new branch based on the reverted changes, e.g., stable-rollback.
  2. Update the Environment Configuration:
    • In your XM Cloud deployment settings, update the environment to use the new stable branch.

3. Rebuild and Redeploy

  1. Trigger the "Build & Deploy" Action in XM Cloud:
    • Go to the XM Cloud interface or your CI/CD pipeline.
    • Select the new stable branch and initiate the “Build & Deploy” action.
  2. Verify the Deployment:
    • Ensure the deployment completes successfully.
    • Validate that the site functions as expected, and all services are operational.

Benefits of This Approach

  • Efficiency: Quickly revert to a stable state without extensive troubleshooting.
  • Control: Maintain full transparency over code changes and deployments.
  • Flexibility: Easily manage multiple stable branches for different environments.
  • Version History: Maintain a clear audit trail of changes and rollbacks for future reference.

By leveraging version control processes, you can effectively manage rollbacks in Sitecore XM Cloud and ensure a smooth deployment experience.

Tuesday, June 11, 2024

Resolving Multiple HTTPS Entries in Sitemap



Issue Observed:

During a recent project, I observed that multiple HTTPS entries were being generated in the sitemap. This issue not only caused redundancy but also had potential implications for SEO and website performance.

After a detailed investigation, I determined that the problem was related to incorrect configuration settings within Sitecore.


Root Cause Analysis

In Sitecore, the configuration for each site defines how URLs are generated, including protocol and host information. The issue was traced to the following path:


/sitecore/content/Site/Settings/Site Grouping/Site1

Within this configuration, the Target Hostname field included the HTTPS protocol, which resulted in duplicate entries being created in the sitemap.

For example:


https://www.example.com

When the sitemap was generated, this setting caused the URLs to be prefixed incorrectly, leading to multiple instances of HTTPS URLs appearing.

Solution

The fix for this issue was straightforward and involved modifying the Target Hostname setting. Here’s how it was resolved:

  1. Navigate to the Site Settings:

    • Go to: /sitecore/content/Site/Settings/Site Grouping/Site1
  2. Correct the Target Hostname:

    • Remove the HTTPS prefix from the Target Hostname field.
    • Instead of: https://www.example.com
    • Use: www.example.com
  3. Save and Publish the changes to ensure they take effect.

Why This Fix Works

Sitecore generates URLs dynamically based on the Target Hostname configuration. By including the protocol (https://) directly in the Target Hostname field, Sitecore was misinterpreting the setting and creating redundant HTTPS entries.

By specifying only the hostname (www.example.com), Sitecore uses the appropriate protocol based on other configurations, ensuring consistent and accurate URL generation in the sitemap.

Results

After implementing this change:

  • The sitemap no longer displayed duplicate HTTPS entries.
  • URL generation was consistent and aligned with best practices for SEO.
  • The overall sitemap was clean, accurate, and free of redundancy.

Key Takeaways

  • Check Hostname Settings: Always ensure the Target Hostname field contains only the hostname, without protocol prefixes.
  • Follow Best Practices: Let Sitecore handle protocol resolution based on your site's configurations for HTTP and HTTPS.
  • Regular Sitemap Audits: Periodically review your sitemap to identify and address any anomalies that may impact SEO.

By maintaining proper settings in Sitecore, you can avoid sitemap issues and ensure a seamless experience for both search engines and users.

For any additional queries or troubleshooting assistance, feel free to leave a comment or reach out. Happy Sitecore-ing!

Thursday, May 9, 2024

How to Use External Images in Image Fields with Sitecore's Page Editor


Recently, while working on a Sitecore project that involved integrating Celum DAM (Digital Asset Management), I encountered a requirement to support external images within Sitecore's Image fields in the Page Editor.

The objective was to enable content authors to:

  1. Add external image URLs directly (e.g., public links from Celum).
  2. Ensure a seamless preview experience within the Page Editor, including dynamic components such as image carousels.

This approach allowed the use of Celum-hosted images while maintaining the intuitive Sitecore authoring experience.

This article outlines the steps, challenges, and solutions for implementing this feature.

The Requirement

The requirement was straightforward:

  1. Source Images Externally: Authors needed to add images via external URLs rather than uploading them to the Sitecore Media Library.
  2. Preview in Page Editor: The images, whether single or in a carousel, had to be visible within the Page Editor for a better authoring experience.

The Challenges

  1. Default Behavior of Image Fields: Sitecore's out-of-the-box (OOTB) Image field retrieves images from the Media Library, not external sources.
  2. Page Editor Compatibility: External image links needed to render correctly in the Page Editor, ensuring authors could see real-time previews.
  3. Handling Multiple Images: For components like carousels, the solution had to handle multiple external image URLs effectively.

Proposed Solutions

1. Using a General Link Field

  • One suggested approach was to use a General Link field instead of an Image field.
  • Authors could paste the external URL into the General Link field, and the rendering component would use this URL to display the image in an <img> tag.

Implementation:


<img src="@Model.Item["ExternalImageLinkField"]" alt="Carousel Image" />

While this approach worked for basic cases, it lacked the functionality of the OOTB Image field, such as alt text management or built-in media selection.

2. Cus
tomizing the Image Field
To provide the desired experience, I created a custom solution:

  • Step 1: Extend the Image Field
    Create a custom field type that allows authors to input external URLs or select an image from the Media Library.

  • Step 2: Update the Rendering Logic
    Modify the component's logic to handle both Media Library images and external URLs:

    csharp

    string imageUrl = item.Fields["ImageField"].Value; if (!imageUrl.StartsWith("http")) { imageUrl = MediaManager.GetMediaUrl(item.Fields["ImageField"].MediaItem); }
  • Step 3: Preview in Page Editor
    Use Sitecore's rendering parameters to enable real-time previews of external images in the Page Editor.

3. Custom Carousel Rendering For handling multiple external images in a carousel:

  • Use a Multilist field or a JSON field to store multiple external URLs.
  • The rendering component processes these URLs dynamically to generate the carousel.

Example rendering logic:

javascript

const images = @Html.Sitecore().Field("CarouselImageLinks", Model.Item); images.split(',').forEach(imageUrl => { <img src="@imageUrl" alt="Carousel Image" /> });

Key Takeaways

  1. Customization is Key: While Sitecore provides robust OOTB functionality, customizations are often necessary to meet specific requirements.
  2. Maintain Authoring Simplicity: Ensure that any solution integrates smoothly with the Page Editor, providing an intuitive authoring experience.
  3. Consider Scalability: Solutions should support single images, multiple images, and future enhancements with minimal rework.

This approach successfully enabled the use of external image URLs in Sitecore's Image fields, ensuring both functionality and usability for authors. By sharing this solution, I hope it helps others facing similar challenges. If you have additional insights or questions, feel free to reach out!

Wednesday, May 8, 2024

How to Revert Item Source from Database to Resources in Sitecore XM Cloud After Template Modification


In Sitecore XM Cloud, templates and items can be stored as resources, ensuring that they remain synchronized with deployments. However, modifying a template directly in the content editor changes its source from "resources" to "database." This presents challenges if you need to revert the source back to "resources," especially with multiple content items linked to the affected template.

Here’s how to revert the item source effectively:

Scenario

  • Problem: A template source was accidentally changed from "resources" to "database."
  • Goal: Revert the template source back to "resources" without disrupting existing content items or performing manual workarounds, like deleting and recreating templates.

Solution: Cleanup Command

Sitecore CLI provides a cleanup command to revert the item source back to resources. This method ensures synchronization during the next deployment.

  1. Run Cleanup Command Use the following command in the Sitecore CLI:


    dotnet sitecore itemres cleanup --path "{{itempath}}" -f -r
    • --path: Specify the path of the item or template to clean up.
    • -f: Forces the cleanup without additional prompts.
    • -r: Recursively applies cleanup to all child items within the path.

    Example:


    dotnet sitecore itemres cleanup --path "/sitecore/templates/Sample Template" -f -r
  2. What It Does

    • Removes database entries for items that exist in the Item-as-Resource (IAR) repository.
    • Reverts items to their original state in the resources folder.
  3. Validation

    • After running the command, verify the source by enabling "Source View" from the View menu in the content editor.
    • The source should now show "resources" instead of "database."

Alternative Approach

If only a few items are affected:

  • Delete the Database Entries:
    • Simply delete the affected items/templates in the content tree.
    • The system will revert to using the resources version of the item during the next deployment.

Considerations

  1. Backup Content:
    Before running cleanup commands or deleting items, ensure content backups are in place to avoid data loss.

  2. Use CLI for Bulk Operations:
    For larger trees, the CLI is the most efficient way to clean up multiple items.

  3. Official Documentation:
    Refer to the official documentation for more details on the cleanup command:
    Sitecore CLI Itemres Cleanup

Conclusion

The dotnet sitecore itemres cleanup command is the ideal solution to revert an item source from "database" to "resources" in a multi-item scenario. For isolated cases, manual deletion of the database entry may suffice. These approaches ensure minimal disruption and alignment with the deployment pipeline.

Thursday, May 2, 2024

How to cleanup the resource file


 Run below command to setup Extensibility

 dotnet sitecore plugin add -n Sitecore.DevEx.Extensibility.ResourcePackage --version 5.2.113

If you find any issue check your latest installed packages

dotnet sitecore plugin list
Cleanup command
dotnet sitecore itemres cleanup --what-if


Other Commands
dotnet sitecore ser push -n "Local"   
npm run start:connected
npm run lint -- --fix 

More details - https://doc.sitecore.com/xp/en/developers/104/developer-tools/the-cli-login-command.html#options

Tuesday, April 30, 2024

Sitecore Search - Crawler error and fix

During the crawler setup, I got below error



While configuring a web crawler for a recent project, I encountered errors related to missing Open Graph (OG) metadata and 404 responses. These issues can significantly impact the efficiency of the crawler and the completeness of the data it collects. Below, I outline the errors encountered and the steps to resolve them.


Error Details

  1. Missing Open Graph Metadata
    The following error was reported during the crawler execution:


    Missing Fields: type Required Fields: type, id

    This error indicates that some pages are missing required Open Graph fields, specifically the type field. Open Graph metadata is critical for ensuring content is properly interpreted and displayed when shared or indexed.

  2. 404 Errors for Certain Pages
    Additionally, some pages returned a 404 Not Found status during crawling. This means the crawler could not access these pages, likely because they were not published or their URLs were incorrect.


Diagnosing the Issues

  1. Missing OG Metadata:
    In Open Graph schemas, the fields type and id are typically mandatory by default. When these fields are missing, the crawler cannot accurately interpret the content.

  2. 404 Errors:
    Pages returning a 404 status need to be reviewed to ensure they are correctly published and accessible.


Step-by-Step Solutions

1. Fix Missing Open Graph Metadata

To resolve the missing OG metadata issue, ensure the following:

  1. Add Required OG Tags:
    Include the necessary Open Graph meta tags on all relevant pages. For example:


    <meta property="og:type" content="article" /> <meta property="og:id" content="unique-id-1234" />
  2. Check for Consistent Placement:
    Ensure the meta tags are consistently placed within the <head> section of every page template. This ensures the crawler can retrieve the metadata reliably.

  3. Automate Attribute Selection:
    If your crawler supports attribute selectors, configure it to extract the type value directly from the page elements. This can serve as a fallback in case the metadata is not hard-coded.

    Example configuration:


    { "typeSelector": "meta[property='og:type']", "idSelector": "meta[property='og:id']" }

2. Resolve 404 Errors

To address pages returning 404 status codes:

  1. Publish Missing Pages:
    Review the list of pages that are returning 404 errors. Ensure these pages are correctly published and accessible.

  2. Verify URLs:
    Confirm that the URLs being crawled are accurate and free of typos or incorrect paths.

  3. Check Server Configuration:
    Ensure your server settings and routing configuration are correctly handling requests for these pages.


Final Recommendations

  • Regularly Validate Metadata:
    Implement automated checks to ensure Open Graph metadata is present on all pages.

  • Crawler Configuration:
    Customize your crawler to handle missing attributes gracefully by defining fallback selectors.

  • Monitor for Broken Links:
    Use tools to periodically scan your website for broken links and 404 errors to maintain data integrity.

By ensuring your Open Graph metadata is properly configured and addressing 404 errors promptly, you can optimize the performance of your web crawler and ensure comprehensive data collection.

If you encounter additional issues or need further assistance, feel free to reach out.

Happy Sitecore Coding and Configuration!

Tuesday, April 16, 2024

Troubleshooting Sitecore XM Cloud: Deployment Process Halted with Status Code 409 - Project and Environment Already in Deployment.


Lately, during the construction and deployment of the UAT environment, all builds were stuck in the queue and failed to respond. Despite numerous attempts to delete the builds, the issue persisted.



After posting about the problem in the Slack channel, we were unable to find a definitive solution. Consequently, we raised a Sitecore ticket, seeking assistance with the issue.


Slack Posted Question - I'm currently encountering an issue with deploying a build on the UAT environment. Despite waiting for several hours, the build remains stuck in the queue.


After canceling the build and attempting to restart the environment, it' showing an message  that the build is still running and it's preventing the restart.

Now, every build is getting queued up. Do we have any options available to resolve this issue? the same branch was successfully deployed to a different environment (Dev) without any issues.

I would greatly appreciate it if anyone who has experienced a similar problem could share their suggestions.

Console error was 

{

    "title": "Not Found",

    "status": 404,

    "detail": "Deployment entity not existing for deploymentId XXXXXXXXXX",

    "traceId": "XXXXXXXXXXXXXXXXXX"

}


There was an issue with our service connection, due to which environment was wrongfully marked as having a running deployment, got fix now.

Slack Reference -  Slack Conversation Link



Tuesday, April 2, 2024

Resolving "Unable to Connect to the Remote Server" in PowerShell with Docker


While working on a recent project involving PowerShell and Docker, I encountered an error that prevented my script from connecting to the local server. The error message was:


Waiting for CM to become available... Invoke-RestMethod : Unable to connect to the remote server At C:\Projects\Project.Web\up.ps1:121 char:19 + ... $status = Invoke-RestMethod "http://localhost:8079/api/http/routers ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

This error indicated that the PowerShell script was unable to establish a connection to the server at http://localhost:8079/api/http/routers. After investigating the root cause, I determined the issue was related to Docker's network configuration.

Solution

Here is the step-by-step process I used to resolve this issue.

1. List Docker Networks

First, identify the existing Docker networks by running the following command:

docker network ls

This command lists all the networks currently created by Docker. The output might resemble:



NETWORK ID NAME DRIVER SCOPE 9b73baa9dff4 bb bb local 2c2b1a85c1a2 host host local 3e8e8a1c32b4 none null local 7e8f1b1d3f44 my_project_network bridge local

2. Remove the Project Network

Identify the network associated with your project and remove it using the following command:


docker network rm <name_of_network>

For example, if the network name is my_project_network, run:


docker network rm my_project_network

This step removes the problematic network configuration, allowing Docker to recreate it with default settings.

3. Rerun the PowerShell Script

After removing the network, rerun your up.ps1 script:


.\up.ps1

This should resolve the connection issue, and the server should now be accessible.

Conclusion

If you encounter similar issues with PowerShell scripts and Docker on Windows, resetting the Docker network configuration can often resolve connectivity errors. If you have any questions or run into additional problems, feel free to leave a comment or reach out.

Happy coding!