Showing posts with label admin. Show all posts
Showing posts with label admin. Show all posts

Saturday, March 22, 2025

Using Sitecore Indexes in PowerShell-Driven Multilist Datasources


If you didn't know, you can point a Sitecore field's datasource to a PowerShell script. It's a super clean way to make dynamic picklists, filtering based on the current item, tags, templates, relationships, you name it.

But if you're pulling a large set of items, you really want to use the search index.

That's where things get weird.

The Find-Item command gives you fast results… but they aren't real Sitecore items. They're search result objects; great for speed, not so great for populating a multilist. Sitecore expects actual items, and when it doesn't get them, your field ends up looking empty.

Luckly, you don't have to abandon the approach completely. The fix is actually a pretty straightforward.


Some Context

For context, you can set the datasource for a multilist to be driven via a script in SPE like this:

In the script definition itself, you can write PowerShell to obtain some set of items from the tree. The resulting list is what shows as applicable for selection on the field.

In theory, you should be able to also utilize the Find-Item commandlet to obtain a list of items from the index. In my case was necessary due the performance implications of running a Get-ChildItem against a massive subtree.

First attempt looked something like this:

So far, so good. You get back a list of items. Or do you?


The Catch

The objects in the $list variable returned by Find-Item are not Sitecore items. They're dynamic search result objects that look like items, walk like items, but won't work in your multilist unless they quack like items.

If you try to return them as-is from your script, you'll find that, even if items were found in the index, the multilist fails to render the items for selection.

The fix? Pretty simple actuallu: Transform the search results back into legit Sitecore items.

Put it all together and you're golden

Now your multilist knows what to do. The search is lightning fast thanks to the index, and authors can pick from relevant matches without sifting through the entire tree.


Why This Matters

This pattern shines when you're working with large content trees or complex tagging structures where traditional item traversal would be painfully slow. By using the index, you're offloading the heavy lifting to Solr, gaining serious performance without sacrificing editor experience.

But more importantly, it calls out a subtle, easy-to-miss SPE gotcha: not all objects returned from PowerShell helpers are Sitecore items. If you're using Find-Item, you'll almost always need a second pass to resolve those results into actual items before they'll work in a field context.

Fail to do that, and you might spend hours wondering why your multilist is coming up empty, despite the index finding exactly what you wanted.

Happy datasourcing! 🚀

Thursday, August 1, 2024

Sitecore MCP 2.0 Roles and Responsibilities Matrix Decoder

TL;DR

I built an app to help me understand the differences in roles and responsibilities between MCP 1.0 and MCP 2.0, and I think it may be helpful for others.  I wanted an easy way to search or browse the different roles and responsibilities and get a clear answer. 

Check it out here:

Sitecore MCP 2.0 Roles and Responsibilities Matrix Decoder App



Navigating the complexities of the Sitecore Managed Cloud PaaS 2.0 roles and responsibilities matrix isn't particularly exciting, especially for those new to the platform or customers moving from MCP 1.0. While I discovered that the roles and responsibilities in MCP 1.0 and MCP 2.0 are fundamentally similar, MCP 2.0 introduces more detailed and specific tasks related to modern cloud infrastructure management and security enhancements.

This week, I built a learning/reference app to help Sitecore customers, developers, architects, operations administrator/support teams, and account/project managers (and myself 😏) easily reference the different roles and responsibilities defined in MCP 2.0. 

The tool sets out to simplify the process of familiarizing oneself with new tasks and responsibilities, making searching and browsing through the matrix far more digestible. Whether transitioning from MCP 1.0 or diving into MCP 2.0 for the first time,

First, let's highlight the key differences between MCP 1.0 and MCP 2.0 roles and responsibilities I noted during my research. 

The RACI Model

The MCP roles and responsibilities matrix is structured using the RACI model, a framework that defines various stakeholders' involvement in completing project tasks or deliverables. Understanding this model is important for effectively navigating the roles and responsibilities within Sitecore Managed Cloud PaaS 2.0.

What is the RACI Model?

RACI stands for Responsible, Accountable, Consulted, and Informed. Each role in the matrix is assigned one or more of these labels to specify their level of involvement in a given activity. 

  • Responsible (R): The person or people who do the work to complete the task. They are responsible for action/implementation. Responsibility can be shared.

  • Accountable (A): The person who is ultimately answerable for the correct and thorough completion of the task. This role is often called "the one who signs off on the work," and only one person can be assigned to this role for each task.

  • Consulted (C): The people who provide information for the project and with whom there is two-way communication. These are typically subject matter experts.

  • Informed (I): The people who are kept up-to-date on progress, often only on completion of the task or deliverable, and with whom there is just one-way communication.

Applying the RACI Model in Sitecore Managed Cloud PaaS

Sitecore applies the RACI model to delineate roles and responsibilities among Sitecore, customers, and partners within the MCP 2.0 environment to ensure all stakeholders understand their part of the bargain.

Here are some examples of how the RACI model is applied:

  • Activation and Termination: For activating the Sitecore Managed Cloud, Sitecore is Accountable (A) and Responsible (R), while the customer/partner is Informed (I).

  • Provisioning of Environments: Sitecore is Responsible (R) and Accountable (A) for creating new environments while the customer/partner is Consulted (C).

  • Application Design and Implementation: The customer/partner is Responsible (R) and Accountable (A) for planning Sitecore software upgrades, while Sitecore is Informed (I).

  • Infrastructure and Server Management: Sitecore handles the initial provisioning checks as Responsible (R) and Accountable (A), with the customer/partner being Informed (I).

Key Differences Between MCP 1.0 and MCP 2.0 Roles and Responsibilities

While both MCP 1.0 and MCP 2.0 maintain a similar structure and overall responsibilities, MCP 2.0 introduces several new and detailed tasks that reflect advancements in cloud infrastructure management and security. Here are the main differences:

Provisioning of Sitecore Environments

MCP 1.0:
  • Create new environment, installation, and initial set up: Sitecore (R, A)
  • Delete existing environment: Sitecore (R, A)
  • Reset existing environment: Sitecore (R, A)
MCP 2.0:
  • Provision Sitecore Managed Cloud production Hub-spoke environment(s): Sitecore (R, A)
  • Provision Sitecore Managed Cloud non-production environment(s): Sitecore (R, A)
  • Provision Sitecore Managed Cloud disaster recovery Hub-spoke environments(s): Sitecore (R, A)
  • Provision Sitecore Managed Cloud “custom customer-owned” Spoke environment: Sitecore (R, A)
  • Delete existing environment: Sitecore (R, A)
  • Reset existing environment: Sitecore (R, A)

Infrastructure and Server Management

MCP 1.0:
  • Perform initial provisioning check: Sitecore (R, A)
  • Scale infrastructure services (Web App, Solr, Azure SQL, Redis cache, and so on): Sitecore (R)
  • Initial Web Application Firewall - deployment and configuration: Sitecore (R)
  • Set up initial security (Azure SQL firewall): Sitecore (R, A)
  • Set up network firewalls and post-deployment security: Customer/Partner (R, A)
  • Set up third-party services (DevOps tools, CDN, databases, and so on): Customer/Partner (R, A)
  • Custom domain setup: Customer/Partner (R, A)
  • Initial setup and configuration of backup services (blobs, database): Sitecore (R, A)
  • Customization of backup schedules and services: Customer/Partner (R)
  • Consolidation of billing: Sitecore (R, A)
  • Infrastructure performance optimization: Customer/Partner (R, A)
MCP 2.0:
  • Initial Azure Front Door with Web Application Firewall - deployment and configuration: Sitecore (R)
  • Network security groups and initial security setup (Azure SQL firewall): Sitecore (R, A)
  • Network firewalls and post-deployment security setup (Azure SQL firewall): Customer/Partner (R, A)
  • Set up third-party services (DevOps tools, CDN, databases, and so on): Customer/Partner (R, A)
  • Custom domain setup: Customer/Partner (R, A)
  • Initial setup and configuration of backup services (blobs, database): Sitecore (R, A)
  • Customization of backup schedules and services: Customer/Partner (R)
  • Consolidation of billing: Sitecore (R, A)
  • Infrastructure performance optimization: Customer/Partner (R, A)

Security: Azure Platform

MCP 1.0:
  • Configure encryption at rest and in motion: Sitecore (R, A)
  • Configure and perform disaster recovery: Sitecore (R, A)
  • Configure host security - hardened OS: Sitecore (R, A)
  • Operating system (PaaS): Sitecore (R, A)
  • Sitecore Cloud operations change management (via ServiceNow): Sitecore (R, A)
  • Azure DDoS standard initial setup: Sitecore (R, A)
  • Azure DDoS standard post-provisioning: Customer/Partner (R)
  • Define basic Web Application Firewall requirements - rule management: Customer/Partner (R, A)
  • Initial deployment security hardening of Sitecore product: Sitecore (R, A)
  • Ongoing security hardening of Sitecore product: Customer/Partner (R, A)
MCP 2.0:
  • Configure encryption at rest and in motion: Sitecore (R, A)
  • Configure infrastructure security logging via Azure Defender for Cloud: Sitecore (R, A)
  • Configure and perform disaster recovery: Sitecore (R, A)
  • Configure CD App service for Azure Zone Redundancy: Sitecore (R, A)
  • Configure host security - hardened OS: Sitecore (R, A)
  • Configure initial network security – Network security groups: Sitecore (R, A)
  • Configure initial network security – VNET and subnets: Sitecore (R, A)
  • Configure initial network security – private link / private endpoint (App service, SQL, Key Vault): Sitecore (R, A)
  • Configure Azure Bastion service: Sitecore (R, A)
  • Implementation of Azure S2S VPN: Sitecore (R, A)
  • Ongoing S2S VPN configuration and client-side management: Customer/Partner (R, A)
  • Operating system (PaaS): Sitecore (R, A)
  • Sitecore Cloud operations change management (via ServiceNow): Sitecore (R, A)
  • Azure DDoS standard initial setup: Sitecore (R, A)
  • Azure DDoS standard post-provisioning: Customer/Partner (R)
  • Define basic Web Application Firewall requirements - rule management: Customer/Partner (R, A)
  • Implement initial Web Application Firewall configuration and rule management (Front Door): Sitecore (R, A)
  • Initial deployment security hardening of Sitecore product: Sitecore (R, A)
  • Ongoing security hardening of Sitecore application: Customer/Partner (R, A)

Why I Built This App

The roles and responsibilities matrix is a critical component of the Sitecore Managed Cloud PaaS 2.0 offering, providing essential information about the tasks and duties of different team members. However, the sheer volume of information can be overwhelming. 

My goal was to create an intuitive and user-friendly tool that would streamline familiarizing oneself with these roles, ultimately enhancing productivity and understanding.

Key Features of the App

The web app is designed to be straightforward and efficient, offering several key features:

  • Search Functionality: Users can quickly search for specific roles or responsibilities using keywords. This feature significantly reduces the time spent sifting through documents.
  • Browse Capability: For those who prefer to explore, the app allows users to browse through the roles and responsibilities in a structured manner, making it easy to find relevant information.

How to Use the App

Using the app is straightforward. Simply visit Sitecore MCP 2 Roles and Responsibilities Matrix Decoder, where you can start searching or browsing through the various roles and responsibilities.

Conclusion

Whether you are a new user trying to understand your role or an experienced professional looking for specific responsibilities, this tool is designed to help you find the information you need quickly and easily.

For a detailed look at the roles and responsibilities, refer to the official Sitecore documentation provided in the app. Feel free to reach out if you have any feedback or suggestions for improvement.

Friday, September 8, 2023

Building Better Reports: 5 Sitecore PowerShell Extensions Functions for Your Toolbelt


When navigating the Sitecore ecosystem effectively, PowerShell extensions aren't just a helpful tool; they're practically a prerequisite. As someone who has spent a substantial amount of time in this space, I have distilled a set of functions that I've found myself using time and time again. 

Join me as I unpack a curated list of five functions that have become staples in my Sitecore toolkit.

Get-IsPublished

The "Get-IsPublished" function checks if a specific item, identified by its ID, is published on a "web" database. It takes an item as input and queries for it against the "web" database using its ID. If it finds the item in the database, it returns "TRUE," indicating that it is published. If it doesn't find the item (i.e., if the item is null), it returns "FALSE", indicating that it is not published.

This is particularly useful for displaying a column in your SPE report to denote if the item is published to the web database:


Get-ItemSitecoreCELink

The "Get-ItemSitecoreLink" function generates a URL to open a specific item in the Sitecore Content Editor. It takes a Sitecore item as input and uses various properties of that item (like its ID, version number, and language) to construct a URL. This URL, when accessed, will open the Sitecore Content Editor with that specific item loaded, allowing for easy navigation directly to the editing interface for that item. 

Please note that the base of the URL ("https://yourcmurl.com/") in this function is a placeholder that you'd replace with your actual Sitecore Content Management URL.

This is useful if the report is exported to Excel or CSV as it provides the direct link to reach the item without manually traversing the tree or searching for the item by GUID.


Get-LinkFieldUrl

The "Get-LinkFieldUrl" function retrieves the URL from a Sitecore item's link field. It takes a Sitecore item as its input and utilizes a regular expression to extract and return the URL stored in a "My Link Field" field. The regular expression is designed to find and capture the URL stored as a value in a link HTML element's URL attribute.  

If the "My Link Field" is not empty and matches the pattern specified by the regular expression, the URL is retrieved and returned. If the field is empty or doesn't match the pattern, the function returns nothing, essentially returning a null value.

This function couples well for reports if you need to extract the URL out of a Sitecore Link Field value to display in your report:

Assert-HasLayout

The "Assert-HasLayout" function checks if a given Sitecore item has a "final layout" defined. It accepts a Sitecore item as its input and uses the built-in "Get-Layout" function to retrieve the final layout details of the item.  If the item has a final layout (meaning the $layout variable is not null or empty), the function returns a "TRUE" string, indicating that a layout is present.

If no layout is found for the item (meaning the $layout variable is null or empty), it returns a "FALSE" string.

Usage example


Get-FormattedDate

The "Get-FormattedDate" function takes a raw date string as its input and attempts to turn it into a more user-friendly date format.

The raw date string is expected to follow a particular "yyyyMMddTHHmmssZ" pattern ("20230908T123456Z" representing September 8, 2023, 12:34:56 PM in Coordinated Universal Time, for example) - which is precisely how Sitecore typically stored DateTime fields in the database.

The function reads this string and converts it to a date format that is more commonly used, which includes the month, day, and year (like "09/08/2023"). If, for any reason, it can't convert the input into a date (maybe because the input doesn't follow the expected pattern), it will simply return an empty string. This way, even if it receives unexpected inputs, it won't crash and will still produce a result, even if that result is just an empty string.

By passing in the raw DateTime field value into the Get-FormattedDate function, the report will convert it to a readable string value when exporting the report to Excel, CSV, or JSON.




Whether you're a seasoned Sitecore developer or just starting out, these 5 functions can become essential tools in your developer toolkit, helping you navigate the complexities of Sitecore with greater ease and efficiency ✌.

Friday, June 23, 2023

Security Bulletin SC2023-003-587441: SPE OnDoubleClick Error

Sitecore has been busy patching security vulnerabilities left and right lately.  The latest as of this post is Security Bulletin SC2023-003-587441

We applied the hotfix to a lower environment but discovered during regression testing the update had broken a key feature of Sitecore PowerShell Extensions (SPE).

After running an SPE report, double-clicking on any result item does not open a new window to the selected item as expected.  Instead, the following error was being thrown in the logs:

ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.<>c__DisplayClass285_0.<ExecuteStepImpl>b__0()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Nested Exception

Exception: Sitecore.Exceptions.AccessDeniedException
Message: Calling Spe.Client.Applications.PowerShellResultViewerList.OnDoubleClick method through reflection is not allowed.
Source: Sitecore.Kernel
at Sitecore.Reflection.MethodFilter.Filter[T](MethodInfo method)
at Sitecore.Shell.Framework.Commands.CommandManager.GetMethodCommand(String command)
at Sitecore.Web.UI.Sheer.ClientPage.Dispatch(String command)
at Sitecore.Web.UI.Sheer.ClientPage.RaiseEvent()
at Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e)
at System.Web.UI.Control.PreRenderRecursiveInternal()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

The main message here:
"Calling Spe.Client.Applications.PowerShellResultViewerList.OnDoubleClick method through reflection is not allowed."

One of the more profound differences noted when comparing the original files against the hotfix files is the `Sitecore.Reflection.Filtering.config`; where we see several entries removed and many new entries related to SPE (Spe.Client.Applications.PowerShellResultViewerList.OnDoubleClick included) have been added


Upon further investigation, it was discovered that in the `OnDoubleClick` definition, an extra trailing space was present:

Removing the space restored the broken double-click functionality on the instance. 

If you find yourself in a similar situation, check this file first and determine if you have any trailing or unexpected spaces within the `methodName,` and remove them before redeploying the file. 

Hope this helps! ✌

Thursday, April 20, 2023

Sitecore Support Security Bulletin SC2023-002-576660: Hotfix vs Patch


Sitecore recently released a Support Security Bulletin SC2023-002-576660 that addresses a vulnerability in the platform. You can find the details of this bulletin in their knowledge base article KB1002979. Some of my team already had questions regarding the recommended approaches for addressing this vulnerability, specifically the differences between applying a hotfix and a patch. In this post, I'll clarify these approaches and discuss how to apply the hotfix to various Sitecore roles.

Two Approaches: Hotfix vs. Patch

The bulletin outlines two approaches to resolve the vulnerability:

  1. Applying as a hotfix
  2. Applying as a patch

The main difference between these two options is that the patch only fixes the known attack vector (a specific method or pathway that cybercriminals have been observed using to exploit vulnerabilities in software or systems). At the same time, the hotfix addresses the vulnerability more comprehensively - covering scenarios beyond the known attack vector. Due to this critical difference, Sitecore strongly recommends applying hotfixes rather than installing the patch. 

Applying the Hotfix to Different Sitecore Roles

The hotfix comes packaged as a `.update` package and can be easily installed using the Sitecore Update Installation Wizard. This process is straightforward for a Content Management (CM) role. However, applying the hotfix to other functions requires additional steps.

For non-CM roles, installing the hotfix on the CM instance is generally recommended, then syncing the changes made with some other cases using your typical development practices. The idea is to ensure the updated files and configurations installed on the CM instance are copied to Content Delivery (CD) or other Sitecore roles to maintain a consistent codebase and configuration.

To manually extract the contents of the .update package, you can use a tool like 7zip without renaming the file. Right-click the file and choose one of the "Extract" options. You can then extract the package.zip to obtain the files from addedfiles, addedfolders, addeditems, and changedfiles folders. 

Alternatively, to 7zip, you can rename the .update file to .update.zip and extract it using Window's built-in zip manager. Once you've extracted the files, you can plan to drop them into the rest of your non-CM XP roles.

It's worth mentioning that your particular solution may already have a previous cumulative hotfix applied. You may need to check your solution to see if any of the extracted files (such as the Sitecore.Kernel.dll) are already referenced to a static hotfix location and make the necessary updates to the solution to reference.

Compare the DLLs and configs against your solution and merge updates wherever necessary.   Skipping this step risks overwriting the installation during a subsequent deployment.

What's in the latest Hotfix?

Looking at 10.0.0 installation, there are 42 file differences between the current solution and the hotfix files:

  • \sitecore modules\Web\ExperienceForms\scripts\form.conditions.js

  • \sitecore\shell\client\Applications\FormsBuilder\Layouts\Renderings\FormDesignBoard\FormDesignBoard.js
  • \sitecore\shell\client\Applications\FormsBuilder\Layouts\Renderings\Composites\SubmitActionsManager\SubmitActionsManager.js
  • \sitecore\shell\Applications\Page Modes\ChromeTypes\FieldChromeType.js
  • \sitecore\shell\Applications\Page Modes\InlineEditingUtil.js
  • \sitecore\shell\Applications\Content Manager\Content Editor.Search.js
  • \sitecore\shell\Applications\Buckets\scripts\ItemBucket.js

  • \bin\Sitecore.Services.Infrastructure.Sitecore.dll
  • \bin\Sitecore.Services.Infrastructure.dll
  • \bin\Sitecore.Services.Core.dll
  • \bin\Sitecore.Services.Client.dll
  • \bin\Sitecore.Mvc.ExperienceEditor.dll
  • \bin\Sitecore.Mvc.dll
  • \bin\Sitecore.Mvc.DeviceSimulator.dll
  • \bin\Sitecore.Kernel.dll
  • \bin\Sitecore.ExperienceForms.SubmitActions.dll
  • \bin\Sitecore.ExperienceForms.Mvc.dll
  • \bin\Sitecore.ExperienceForms.dll
  • \bin\Sitecore.ExperienceForms.Data.SqlServer.dll
  • \bin\Sitecore.ExperienceForms.Client.dll
  • \bin\Sitecore.ExperienceForms.Analytics.dll
  • \bin\Sitecore.ExperienceExplorer.Web.dll
  • \bin\Sitecore.ExperienceExplorer.dll
  • \bin\Sitecore.ExperienceExplorer.Core.dll
  • \bin\Sitecore.ExperienceExplorer.Analytics.dll
  • \bin\Sitecore.ExperienceEditor.Speak.Ribbon.dll
  • \bin\Sitecore.ExperienceEditor.Speak.dll
  • \bin\Sitecore.ExperienceEditor.dll
  • \bin\Sitecore.ContentSearch.SolrProvider.dll
  • \bin\Sitecore.ContentSearch.SolrNetExtension.dll
  • \bin\Sitecore.ContentSearch.Linq.Solr.dll
  • \bin\Sitecore.ContentSearch.Linq.dll
  • \bin\Sitecore.ContentSearch.dll
  • \bin\Sitecore.ContentSearch.Data.dll
  • \bin\Sitecore.ContentSearch.ContentExtraction.dll
  • \bin\Sitecore.ContentSearch.Client.dll
  • \bin\Sitecore.Content.Services.dll
  • \bin\Sitecore.Client.dll
  • \bin\Sitecore.Buckets.dll
  • \bin\Sitecore.Buckets.Client.dll

  • \App_Config\Sitecore\Services.Client\Sitecore.Services.Client.config
  • \App_Config\Sitecore.config

Conclusion

When addressing the vulnerability outlined in Sitecore Support Security Bulletin SC2023-002-576660 - or others where .update files are provided as part of the solution, applying the hotfix rather than the patch is strongly recommended. The hotfix should be installed on the CM instance and synced with other cases using your regular development practices. This ensures a consistent codebase and configuration across all Sitecore roles.

Hopefully, this helps clarify the recommended approaches for addressing this and future vulnerabilities in Sitecore.

Tuesday, February 28, 2023

Sitecore xDB Contact Lookup Utility

My client's lead flow includes capturing form data into a custom database. Each record contains an xDB Contact ID to correlate the data with the data captured in xDB directly.  We had a scenario where we had hundreds of records in the custom database where the xDB contact ID was missing, likely due to a networking issue between the CD and xConnect.

I needed a way to match users captured in the custom database against the data in xDB to obtain an existing xDB contact ID.  Luckily, Sitecore's documentation provides some sample code to help get me started: xConnect Client API (C#) (sitecore.com)

Thus was born, the...

🧰 xDB Contact Lookup Utility


The utility is your standard .aspx file that can be dropped into the/sitecore/admin folder or at the root of CM instance. It combines a series of xConnect API calls to search for contact information in the xDB.  Applicable parameters include email address, first name, last name, or xDB contact ID.

It can be used in two ways:

First, through the UI (as shown above), you have the ability to populate text boxes to obtain parameters and view the result list on the page.

Secondly as a simple rest endpoint, with the ability to pass parameters into the URL and return a JSON response containing a matching xDB contact ID.

For example: 
/xDB-Contact-Lookup.aspx?email=test@test.com&firstName=test&lastName=test




👨‍💻 Code Breakdown

Page_Load

The Page_Load event checks if a query parameter named "email," "lastName," or "firstName" are present in the URL. 

If at least the "email" parameter is present, the method calls the SearchForContactIdByEmail .If the lastName and firstName parameters accompany the email parameter, the SearchForContactIdByName method is also used to search for a contact. The search results are returned as a JSON response which contains an xDB contact ID of the first match or "NoMatch" if no match was found. The JSON string is written to the HTTP response, ending the response. If the "email" query parameter does not exist, the method does nothing and loads the UI.

btnLookup_Click

This button click handler retrieves user input from four text boxes for known contact ID, email, last name, and first name. If the user input is for a known contact ID, it calls the SearchForContactById method to retrieve the contact's information and displays it in an HTML table. 

If there is no matching contact, it displays a message saying that no contact was found. 

If the user input is for email, last name, and/or first name, it calls SearchForContactIdByEmail and/or SearchForContactIdByName methods to retrieve contact information and displays it in an HTML table. 

If there are no matching contacts, it displays a message saying that no contact was found.

There are three methods implemented for using the xConnect API:

SearchForContactById

This method searches for a Contact object in xDB using a known contact ID. The method SearchForContactById takes a string parameter knownContactId and returns a Contact object. The method first converts the knownContactId string to a Guid, creates an instance of Sitecore.XConnect.Client.XConnectClient, and uses the Get method of the client object to retrieve a Contact object using a Sitecore.XConnect.ContactReference object created from the Guid

It also uses a Sitecore.XConnect.ContactExpandOptions object to specify which facets of the Contact object to retrieve. 

If the Get method throws an XdbExecutionException, the method catches the exception and returns null.

SearchForContactIdByName

This method searches for a list of Contact objects by their LastName and FirstName facets of PersonalInformation

SearchForContactIdByName takes two string parameters, lastName and firstName, and returns a list of Contact objects. 

Inside the Sitecore.XConnect.Client.XConnectClient using block, the method creates an IAsyncQueryable object named queryableLastName that represents a xConnect API query to xDB. The query retrieves all contacts where the LastName and FirstName facets of PersonalInformation match the values of the lastName and firstName parameters. 

The query then sorts the results in descending order of LastModified. The WithExpandOptions method is used to specify which facets of the Contact object to retrieve. The method then retrieves the query results using a batch enumerator, which is added to a List<Contact> object named idsList. 

If the query throws an XdbExecutionException, the method catches the exception and returns null.

SearchForContactIdByEmail

This method searches for a list of Contact objects by their EmailAddress and optionally their LastName and FirstName facets of PersonalInformation

SearchForContactIdByEmail takes three string parameters, email, lastName, and firstName, and returns a list of Contact objects. 

Inside the using block, the method creates an IAsyncQueryable object named queryable that represents a xConnect API query to the xDB. The query retrieves all contacts where the PreferredEmail facet of EmailAddressList matches the email parameter value. 

The query then sorts the results in descending order of LastModified. The WithExpandOptions method is used to specify which facets of the Contact object to retrieve. The method then retrieves the query results using a batch enumerator, which is added to a List<Contact> object named idsList

If the firstName and lastName parameters are not empty, the method checks if the FirstName facet of PersonalInformation and LastName facet of PersonalInformation match the values of the firstName and lastName parameters respectively for each Contact object retrieved. 

If both match, the Contact object is added to idsList. If the firstName and lastName parameters are empty, all Contact objects retrieved are added to the idsList

If the query throws an XdbExecutionException, the method catches the exception and returns null.

Final Result

The full code can be copied here. Add the content to a .aspx file and place it where you need it.


As always, feel free to modify or build on top of this to satisfy your own requirements.

🚀


Tuesday, December 13, 2022

Sitecore Analytics Database Manager (ADM) Contact Outliers - No Contact IDs Displaying

I recently installed the Analytics Database Manager (ADM) v10.0.2 module on a Sitecore 10.0.0 site. After completing the setup, I noticed that the xDB Contact Outliers report failed to render the Contact ID column in the table.


When I checked the browser's console, I saw that the data was indeed present in the dataset. The challenge was that the front-end code was closed-source and compiled in Angular, making it difficult to modify.

Since the Analytics Database Manager is distributed "as is" and not supported in the scope of the Sitecore Support Program, I had to try to resolve this myself. 

I searched for the `.NumberOfInteractions` property in the compiled ADM code since it was a unique enough property related to the data set that should point me in the right direction.

Luckily, I found a hit at `\sitecore\shell\client\Applications\ADM\main.577d3292f13f80d19c29.bundle.js`.

Next to it, I found what appeared to be the definition for the Contact ID column. However, the property `.id` did not match the data object's `Id` as seen in the console (note the capitalization). 



The table populated as expected by capitalizing the `i' in `Id`.



I hope this helps anyone who may encounter the same issue.



UPDATE
Sitecore released new versions of the module that address this issue on February 01, 2023:
https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB0232559




Monday, September 26, 2022

Copy Sitecore User Roles from One User to Another User using Sitecore PowerShell

I recently had received a request to add several new Content Author accounts to the CMS and apply the exact user roles from a specific user to the new users.  I ended up scripting this with Sitecore PowerShell Extensions using hardcoded variables (usernames and roles), but because I expect similar requests in the future, I wanted a quick way to copy roles from one user account to another to use in the future.  Since I couldn't find a script readily available to do this, I developed my own. 

The script utilizes the 'user' editor type (which doesn't happen to be listed on https://doc.sitecorepowershell.com/interfaces/interactive-dialogs - yet still works) within an interactive 'Show-ModalDialog.' It allows you to select a "source user" and a "target user" from the list of all available user accounts.  After choosing both, the script iterates through each source user's roles and applies the target user to each user role. 

The script loads the modal and requires the user to select a Source User and Target User.

Clicking the ellipses button opens a separate dialog that lists all users. 



After selections are made, click OK to initiate the copying of roles. 

The script can be run in Sitecore PowerShell ISE or configured as a module that can be run from the Start Menu.

Happy scripting! 🦸‍♂️

Thursday, July 7, 2022

Sitecore Icon Search 2022 Web App and Extensions Updates + Microsoft Edge Addon v1.0.0 Release

It's been 671 days since the last update to the Sitecore Icon Search web app and 1,278 days since my last update to the Chrome and Firefox extensions. I've made updates to squash new bugs across the Sitecore Icon Search ecosystem that have surfaced since the previous release while mitigating the extensions' delisting at the beginning of 2023. 

WebApp: Sitecore.com dependency migration. 


I recently visited sitecoreicons.com only to find that all icon images failed to load. 😢

For context, by default, the app has always used www.sitecore.com to source the icon images themselves since sitecore.com happens to be a Sitecore site. Given how lazy loading is implemented in the data table, I always expected the strain on www.sitecore.com to have remained minimal.  

It turns out Sitecore has recently implemented DDOS security protection via Cloudflare. You might notice that if you go to www.sitecore.com, you'll land on a screen that looks like this before you are redirected to the site:



Due to this change, it left sitecoreicons.com imageless.   The latest updates to the Web app resolves this by hosting the icon images within the application - cutting out the dependency on www.sitecore.com completely. The browser extensions have also been updated to source icon images from sitecoreicons.com


Chrome Extension: Critical Manifest Updates to avoid looming January 2023 Deadline

The Sitecore Icon Search Chrome extension is actively used by ~500 active users. When I originally built the extension, the latest 'manifest' version (a JSON file containing information that defines the extension) was v2.  

Google has provided two critical dates as manifest v2 is deprecated and replaced entirely with v3.  

January 17, 2022: New Manifest V2 extensions will no longer be accepted by the Chrome Web Store. Developers may still push updates to existing Manifest V2 extensions, but no new Manifest V2 items may be submitted.

January 2023: The Chrome browser will no longer run Manifest V2 extensions. Developers may no longer push updates to existing Manifest V2 extensions.

This means that the Sitecore Icon Search Chome extension will no longer function after January 2023 and, in its current state, cannot be updated until upgraded. The latest release brings the extension's manifest version up to version 3 and provides code fixes for several deprecated APIs that surfaced with the upgrade. 


By default, Chrome should update to the latest version automatically. 


Firefox Add-on: Revival

Back in December 2021, I received an email from the Mozilla team regarding a policy update that I, unfortunately, hadn't found time to respond to.   This results in version 1.0.0 of the Firefox add-on being removed 😢


Version 2.0.0 of the Firefox addon contains all the latest updates made for the WebApp and the Chrome extension and resolves the policy issues. I'm actively awaiting the add-on approval process to conclude and will update this portion of this blog post once the extension is available.   


UI and UX enhancements 

While I was making some updates, I at least decided to have a little fun. I've updated some fonts and scattered emojis across the app. I've also included some phrases catered to Gen-Z Sitecore developers. 😁






Microsoft Edge Addon v1.0.0 Release

While Chrome Extensions can already be added to Microsoft Edge by toggling on a feature, however, to avoid requiring Edge users to jump through hoops, I've decided to port and release the Microsoft Edge version of the browser extension. Version 1.0.0 can be downloaded on the Microsoft Add-ons library.



Monday, May 9, 2022

Latest Azure PaaS Sitecore Logs using a single line of PowerShell

If you’re anything like me, you probably don’t have a passion for manually digging through the series of hundreds of randomly dated folders that look like this in search of the latest Sitecore logs:


Hello darkness, my old friend

Although several tools and approaches are available (including this nifty tool credited to fellow Sitecore MVP Kiran Patil - as well as some of my own previous posts from 2018 and 2019 covering this topic), I've recently adopted a different strategy that's proved to be successful across several Sitecore PaaS clients for quickly obtaining the latest physical Sitecore log for a given server. 

The post-worthy kicker?  It's one line of PowerShell:

$kuduHost = "https://yourazuresitename-xp2-cd.scm.azurewebsites.net"; Write-Output "`n[ LATEST SITECORE LOGS ]`n"; $array = @(); Get-ChildItem "C:\home\site\wwwroot\app_data\logs" -File -Recurse | Where-Object { $_.FullName -match "azure.*.txt" -and $_.LastWriteTime -gt (Get-Date).AddHours(-12) } | ForEach-Object { $path = $_.FullName.replace("C:\home\site\wwwroot\app_data\logs\", "$kuduHost/api/vfs/site/wwwroot/App_Data/logs/"); $array += "`n[$($_.LastWriteTime)]`n$path`n"}; $array | Sort-Object $_.LastWriteTime | Select-Object -Last 3

😬

Okay, it's...kind of a long one-liner...but one line nevertheless 

The above example outputs direct links to the latest three physical Sitecore log files, which match the pattern 'azure.*.

In practice, the desired file can be highlighted from the console and at which point you can copy the URL or open it in a new tab.



Let's break it down

The first line defines a variable for the KUDU host you're using:

$kuduHost = "https://yourazuresitename-xp2-cd.scm.azurewebsites.net"

The second line outputs a (wholly arbitrary and unnecessary) title:

Write-Output "`n`[ LATEST SITECORE LOGS ]`n"

The third line represents an array variable aptly named `$array` (because I'm clever):

$array = @();

This is where it gets exciting. This Get-ChildItem cmdlet gets all files recursively under the site's `\App_Data\logs` location:

Get-ChildItem "C:\home\site\wwwroot\app_data\logs" -File -Recurse
Neat!

We can pipe in a Where-Object cmdlet to filter only file names that match 'azure.*.txt' (or if you want all log types - Publishing, Crawling, Dianoga, SPE, etc. - *.txt) and provide a 12-hour threshold against the `LastWriteTime` property:

Get-ChildItem "C:\home\site\wwwroot\app_data\logs" -File -Recurse |
Where-Object {$_.FullName -match "azure.*.txt" -and $_.LastWriteTime -gt (Get-Date).AddHours(-12)}

We can then pipe in a ForEach-Object cmdlet to iterate through each file:

Get-ChildItem "C:\home\site\wwwroot\app_data\logs" -File -Recurse | Where-Object { $_.FullName -match "azure.*.txt" -and $_.LastWriteTime -gt (Get-Date).AddHours(-12) } | ForEach-Object { $path = $_.FullName.replace("C:\home\site\wwwroot\app_data\logs\", "$kuduHost/api/vfs/site/wwwroot/App_Data/logs/"); $array += "[$($_.LastWriteTime)]`n$path`n"}

Notice that in the ForEach-Object cmdlet, we create a variable called `$path` and set it to a string that takes the file's FullName and replaces the 'system path' portion, and replace it with our `$kuduHost` variable concatenated to `/api/vfs/site/wwwroot/App_Data/logs/`.

$path = $_.FullName.replace("C:\home\site\wwwroot\app_data\logs\", "$kuduHost/api/vfs/site/wwwroot/App_Data/logs/")

Without this string replacement, we'd only get the system path for the files in the dataset, which would still require navigating to the file manually:

Also, within the ForEach-Object cmdlet, a formatted string containing the LastWriteTime and the `$path` variable is added to the `$array` variable:

$array += "[$($_.LastWriteTime)]`n$path`n"

The `n used above allows for line breaks.

After the files have been processed, the `$array` variable is called and sorted by LastWriteTime.

A Select-Object cmdlet is piped in to limit the number of results to 3:

$array | Sort-Object $_.LastWriteTime | Select-Object -Last 3


By combining these together, eliminating spaces, and adding semi-colons to separate commands, we've got our one-liner! 🕺

Bonus: IIS HTTP Request Logs

Using the same approach with a few modifications, the application's raw IIS HTTP Request Logs can also be obtained (differences bolded below):

$kuduHost = "https://yourazuresitename-xp2-cm.scm.azurewebsites.net"; Write-Output "`n[ LATEST IIS LOGS ]`n"; $array = @(); Get-ChildItem "C:\home\LogFiles\http\RawLogs" -Recurse | Where-Object { $_.FullName -match ".log" -and $_.LastWriteTime -gt (Get-Date).AddHours(-12) } | Sort-Object $_.LastWriteTime | ForEach-Object { $path = $_.FullName.replace("C:\home\LogFiles\http\RawLogs\", "$kuduHost/api/vfs/LogFiles/http/RawLogs/"); $array += "[$($_.LastWriteTime)]`n$path`n"}; $array | Sort-Object $_.LastWriteTime | Select-Object -Last 3


Final Thoughts

You can generate variations of this one-liner by changing the various variables, which can be shared with the rest of your development/troubleshooting team and readily ready to copy from an internal Wiki:

Feel free to use and modify the script as you see fit. 🚀

Thursday, September 23, 2021

Sitecore Cache Tuning: LAYOUT_DELTA_CACHE

While tuning caches for a production level Sitecore 10.0.0 site, I came across a cache name I was unfamiliar with using a cache tunerLAYOUT_DELTA_CACHE


There were also log entries specific to this cache:

4484 12:07:57 INFO Cache created: 'LAYOUT_DELTA_CACHE' (max size: 50MB, running total: 6580MB)

Oddly enough, at the time of this post, no Google Search results mentioned this cache name.


Sitecore's documentation also had no mention of the setting either. 

Reaching out to Sitecore Support helped clarify things, and I wanted to share in case anyone else happens to come across this same cache that needs tuning. 

"The cache seems to be utilized when applying layout deltas when Sitecore is retrieving the layout field. The default size of this cache is 50MB, however, you can modify it with the "Caching.LayoutFieldDeltaCacheSize" setting."

Check out the following example configuration:


Hopefully, this helps with your Sitecore cache tuning activities. Happy tuning! 😊

Thursday, April 9, 2020

RIP Sitecore App Center: Remove and Re-purpose Sitecore App Center Shortcuts with PowerShell

Last week, while we were all preoccupied with COVID-19, Sitecore did something nobody could have predicted. Between the chaos, our beloved Sitecore App Center was discontinued.

Not many people seemed to care about my PSA, though:

This probably would have generally slipped past me until months after the update, but this happens to come to my attention because a client wanted to start using GeoIP functionality in Sitecore in the middle of their transition to retiring the aged feature. The stars aligned, and I was fortunate enough to watch it all unfold before my very eyes. 


Until now, Geo IP Service activation had always been a two-part process:

     1) Guide the client to sign up for the Geo IP Service in the Sitecore App Center - which happened to be baked into the CMS, sourced out to an external endpoint, and required customer login (partners typically didn't have access to log in and activate anything).

     2) Make the necessary configuration and firewall updates.

The options were endless. 


The client immediately reported an issue loading the Sitecore App Center.



Lo and behold; a broken App Center (all environments, including local):


Sitecore's Cloud Status page happened to indicate that the App Center UI was "under maintenance" at the time.

This was on March 30th, a couple days after their maintenance window had closed.
Wow - month-long maintenance windows. 
Must be nice.  


Two days later - after much anticipation - an update was posted:


In addition to this status page update, the Sitecore documentation was updated to reflect the updated Sitecore Support Portal approach for activating the Geo IP Service:
Gotta love that freshly updated documentation scent.

Okay, cool.  I think that makes things a bit easier going forward.


But what about the Sitecore App Center Applications shortcuts in the Launchpad and Start Menu?  



A quick search targeting the Core DB revealed those item definitions.


The specific items that control the shortcuts are:

LaunchPad
Name: AppCenter 
ID: {F7F3379C-A034-4CE4-B2F7-9BDFC3F05A2B} 
Template: LaunchPad-Button 
Path: /sitecore/client/Applications/Launchpad/PageSettings/Buttons/Tools/AppCenter

For this shortcut, you have a few options:
   1) Delete it
   2) Move it outside of the Tools folder and into the PageSettings folder
   3) Edit the Link field to point to the permanent Sitecore Cloud Status Page related to this event

I prefer option 3 because it could at least potentially help guide future devs or marketers in the right direction when activating the GeoIP service - specifically if it had always remained off.




Start Menu
Name: Sitecore App Center 
ID: {A59E3738-08E1-49EA-9199-E0140F56C67D} 
Template: Application shortcut 
Path: /sitecore/content/Documents and settings/All users/Start menu/Left/Sitecore App Center

This Application Shortcut item is better off removed or disabled, rather than repurposed.  Attempting to load an external link won't work with this template type (or any of the other applicable template types for this location).

To disable the shortcut, clear out the Application field.


👍

Script

If you don't want to do this manually - or you're strapped for time - you can, you know..just run this PowerShell script 😉:

The script disables the Start Menu shortcut, then gives the option to repurpose or disable the Launchpad shortcut:


⚰ RIP Sitecore App Center

Thursday, September 5, 2019

Azure Application Insights: Logs & Requests Viewer using Sitecore PowerShell Extensions

Last September, I wrote about accessing Sitecore Logs from Azure PaaS instances using the (now deprecated) AzureAILogs.html file provided by Sitecore. The knowledgebase article was updated in mid-January , 2019 – and the AzureAILogs.html file had been replaced with a new /sitecore/admin page dubbed AzureTools.aspx.

This updated admin page contains all the same functionality found in the AzureAILogs.html, with the addition of being able to pull log traces and requests from Application Insights.



Installation is easy: download the AzureTools.zip files, drop in the /sitecore/admin/AzureAILogs.aspx into the you’re your site’s root.

Admittedly, this admin page is great - but I could also see several aspects SPE being particularly useful (like the OOB SPE ListView - which would easily allow us to filter/sort/search through a series of log entries). An additional option to see raw color-coded logs would also be cool. 😊

Using the existing AzureTools.aspx as a general guide, we can re-create the GUI with general ease.

We’ll need:
1) Option to get Requests or Logs
2) Option to selected a Role (values pulled from API)
3) Option to control recency.
4) Option to control the severity.


The end result will consume the Application Insights REST API endpoints and allow a user to pull logs from Application Insights inside the CMS.


API Access

To start, we'll need to make sure we can work with the API by obtaining an Application Insights App ID and a corresponding App Insights API key  Sitecore's documentation already lists the.

Sitecore's documentation covers this but it's as simple as logging into Azure Portal and navigating to your Application Insights service. 

Under Configure, select 'API Access':


The Application Insights App ID will be displayed the following screen:

Copy this value and store it temporarily.

Click the 'Create API Key' button.
Give it a name and check the 'Read telemetry' checkbox.

After clicking 'Generate key', you'll have one opportunity to copy the 'App Insights API key'.  Copy and store this value temporarily.


Initial Communication with the API

Our script will utilize the two values to interact with the API.

Before building our UI in SPE, we'll need to confirm API communication by obtaining the server roles from Application Insights.  We can set a variable to call a function that will grab an ArrayList of roles:

Our function will build the URL, include the property URL authorization header containing the API key, and return an array list.



User Interface

Now that we have confirmed communication to the API and obtained our list of roles, we can pass the variable into a new function that will be responsible for building and displaying the UI:

The dialog should contain a series of radio buttons and checkbox lists, all of which will be used to provide options to build out another API call to obtain the traces or requests from AppInsights.

The output displays as follows:

Notice line 51 in the above snippet calls a Get-LogsOrRequests function which accepts a series of parameters from the dialog options upon selecting the OK button.

This function builds out the proper API URL and query parameters based on the passed the selected values passed in. Invoke-WebRequest is used to make the call to the API, which will return a JSON object of log entries from AppInsights based on those parameters.

Line 119 contains a final call to a function called 'Set-PostDialog' which provides options for displaying the results.

The output here is a ModalDialog with three buttons:


Selecting 'Script View' will display the results of the API in a color-coded Show-Result window:


Selecting 'List View' will process the results to an acceptable format for a standard SPE ListView result window (filtering, exporting, etc is obviously all included here):


Finally, selecting the 'Download' button will download a .txt file of the contents retrieved from the API.


Final Script





Installation

Manual

  1. Create a new Sitecore item based on the SPE PowerShell Script template and copy the final script above into the Script Body field.
  2. Replace the default "XXXXXXXXXXXXXXXXXXXXXXXXX" placeholder values in the $aiAppID and $apiKey variables with your own.  

Sitecore Package

  1. Download the Sitecore package and install from GitHub.
  2. Navigate to the PowerShell script located here:
    /sitecore/system/Modules/PowerShell/Script Library/Azure Application Insights Logs/Toolbox/Azure Application Insights Logs
  3. Replace the default "XXXXXXXXXXXXXXXXXXXXXXXXX" placeholder values in the $aiAppID and $apiKey variables with your own.  
The script will be available to run from the PowerShell Toolbox in the Start Menu.


Source Code

The full script can also be found on GitHub.
Feel free to grab a copy and modify it how you see fit.