Tuesday, January 3, 2023

jss start or jss build failed due to error in digital developed routines

 Getting the below error when we try to run jss build or jss start after creating the reactjs app in Sitecore JSS. 

"error:0308010C:digital envelope routines::unsupported"

Solution:

Open the terminal and run the below command

$env:NODE_OPTIONS = "--openssl-legacy-provider"


Wednesday, August 10, 2022

Using Sitecore powershell for Item creation in Sitecore

 Lets try creating a sitecore item through powershell script. 

    $itemName = "new-item-name"

    $itemPath = "master:/sitecore/content/" + $itemName

    $newItem = New-Item -Path $itemPath -ItemType "template-name"

    $newItem.Editing.BeginEdit()

    $newItem["fieldname"] = "fieldvalue"

    $newItem.Editing.EndEdit()


This way of creating Sitecore items using powershell api comes in handy when we want to import Sitecore items from a static source of data i.e., a csv file or json. 

Lets see how to import sitecore item when we have the relevant records in a csv file. 

$importedData = Import-Csv -Path csv-path.csv

foreach($data in $importedData){

    $itemName = $data.Name

    $itemPath = "master:/sitecore/content/" + $itemName

    $newItem = New-Item -Path $itemPath -ItemType "template-name"

    $newItem.Editing.BeginEdit()

    $newItem["fieldname"] = $data.fieldvalue

    $newItem.Editing.EndEdit()

}

A Sample import of complete content migration. 
#Define path you want to create sitecore Items
$parentPath = "master:/sitecore/content/ctscareers/Home/ArticleListing"
#Read CSV file
$importList = Import-CSV "C:\\CSV\\SampleFileToImport.csv"
foreach($row in $importList) {
    $name = $row.Name
    #Check if Title is not empty
    if ($name.Trim() -eq "")
    {
        write-host "Item name should not be blank: " $name
        continue
    }
    $itemPath = $parentPath + "/" + $name #Create Item path
    
    $mediaitemCreated = UploadImageIntoMediaLibrary($row.ImageUrl)

    $currentItem = Get-Item -Path $itemPath -ErrorAction SilentlyContinue #Get the sitecore Item
    if ($currentItem -eq $null) #Check if Item is null then create new Item
    {
        try {
            $item = New-Item -Path $itemPath -ItemType "/sitecore/templates/Feature/CTSTraining/ArticleDetail"
            write-host "Item created: " $itemPath
        }
        catch
        {
            write-host "Failed to create Item: " $itemPath
            write-host $_.Exception.Message
            continue
        }
    }
    #Assign Field values to the Sitecore Item
    $item.Editing.BeginEdit()
    $item["PageTitle"] = $row.PageTitle
    $item["ArticleTitle"] = $row.ArticleTitle
    $item["ArticleBrief"] = $row.ArticleBrief
    $item["MetaTitle"] = $row.MetaTitle
    [Sitecore.Data.Fields.ImageField]$imageField = $item.Fields["OGImage"]
    $imageField.MediaID = $mediaitemCreated.id
    $item.Editing.EndEdit()
}

function UploadImageIntoMediaLibrary{
    [CmdletBinding()]
    param([Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
          [ValidateNotNullOrEmpty()]
          [string]$filePath)
          
    $mediaPath = "/sitecore/media library/Images"
    $mediacreatoroptions = New-Object Sitecore.Resources.Media.MediaCreatorOptions
    $mediacreatoroptions.AlternateText = "$([System.IO.Path]::GetFileNameWithoutExtension($filePath))"
    $mediacreatoroptions.Database = [Sitecore.Configuration.Factory]::GetDatabase("master");
    $mediacreatoroptions.Language = [Sitecore.Globalization.Language]::Parse("en")
    $mediacreatoroptions.Versioned = [Sitecore.Configuration.Settings+Media]::UploadAsVersionableByDefault;
    $mediacreatoroptions.Destination = "$($mediaPath)/$([System.IO.Path]::GetFileNameWithoutExtension($filePath))";
    
    $mediacreator = New-Object Sitecore.Resources.Media.MediaCreator
    $newmediaitem = $mediacreator.CreateFromFile($filePath, $mediacreatoroptions)
    return $newmediaitem
    
}

Thursday, June 23, 2022

Import Service not working in JSS Deploy App

 I was puzzling for a long time why my import service call in the terminal was always giving error. 

Unexpected response from import service:

This is because the import service that you call is not SSL Certified and even if we add a self signed certificate, we would get the below error as 

Unexpected response from import service:

Now to make it work, we need to enable https for the domain 

self signed certificate

Open powershell in admin mode and provide the below script. 

New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\my -DnsName "*.local" -FriendlyName "*.local" -NotAfter (Get-Date).AddYears(25)

and then accept the certificate thumprint with the below command. 

jss deploy app -c -d --acceptCertificate "c2b764d098f7793f628f22af4ffc883cb92aafe0"

Sunday, March 13, 2022

Computed index for item url in Sitecore

 Normally, sitecore will not index the item url in Solr. We may need to create a computed index for the same, 

However, the challenge is that when we try to generated the url using Link Manager, system would throw "object reference not set to an instance of an object" error, as the Site and Item context is not available during computed index execution. 

So, in order to get the url indexed, we should follow the below steps,

Code:

        public object ComputeFieldValue(IIndexable indexable)
        {
            Item sitecoreItem = indexable as SitecoreIndexableItem;
            if (sitecoreItem == null)
                return null;
            if (sitecoreItem.TemplateName != "<templatename>")
                return null;
            var siteContext = SiteContextFactory.GetSiteContext("<sitename>");
            Sitecore.Context.Site = siteContext;
            Sitecore.Context.Item = sitecoreItem;
            ItemUrlBuilderOptions itemUrlBuilder = new ItemUrlBuilderOptions
            {
                SiteResolving = true,
                AlwaysIncludeServerUrl = false,
                LowercaseUrls = true
            };
            var articleUrl = LinkManager.GetItemUrl(sitecoreItem, itemUrlBuilder);
            return articleUrl;

        }


Config:

<?xml version="1.0"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">

<sitecore>

<contentSearch>

<indexConfigurations>

<defaultSolrIndexConfiguration>

<fieldMap>

<fieldNames hint="raw:AddFieldByFieldName">

<field fieldName="ArticleUrl" returnType="string" />

</fieldNames>

</fieldMap>

<documentOptions>

<fields hint="raw:AddComputedIndexField">

<field fieldName="ArticleUrl" returnType="string">

<<ClassFullyQualifiedName>>.<<AssemblyName>>

</field>

</fields>

</documentOptions>

</defaultSolrIndexConfiguration>

</indexConfigurations>

</contentSearch>

</sitecore>

</configuration>


Monday, March 7, 2022

How to add datasource for a multilist with search field in Sitecore

 The normal way of adding datasource for multilist field will not working for multilist with search. 

For multilist with search, internally the class is using a bucketted list class to search for the items to be displayed on the left pane. 

Solution:

use this string, StartSearchLocation before the datasource ID and we get the datasource searched. 

StartSearchLocation={AAAF5DC8-662A-4B8C-9E66-52EF5EEDCA20}
Also, we should note here that the data is coming from solr, so if you think the multilist field is still not displaying the items in the left pane, consider doing a rebuild of index. 


Sunday, February 20, 2022

Creating Self Signed Certificate for a wild card domain

 For creating a Self Signed Certificate, 

Step 1:

Open windows powershell in admin mode and enter the below command,

New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\my -DnsName "*.<domainname>" -FriendlyName "*.<domainname>" -NotAfter (Get-Date).AddYears(25)

Post running this, your self signed certificate will be created

Step 2:

Open microsoft management console Start > Manage User Certificate > 


The certificate that we created will be under Personal > Certificate. 

We can simply click on them and COPY and then come to the Trusted Root Certification Authorities > Certificates and then PASTE your certificate. 

Alternatively, we can also export the certificate from the Personal Certificate section and import it back into the Trusted Root Certification Authorities. 


Sitecore CLI - Troubleshooting - GraphQL Service Error

When we use Sitecore CLI sometimes, we land up in getting the below error,

"Make sure the GraphQL service is installed and available".


This issue can happen in two different cases,

Scenario 1: If you dont have the Management Services package installed in your sitecore instance. 

Ref this link:

https://doc.sitecore.com/xp/en/developers/101/developer-tools/sitecore-management-services.html

https://dev.sitecore.net/Downloads/Sitecore_CLI.aspx

Download the Sitecore Management Services Module ZIP Package compatible with your Sitecore version. 

Check the relevant compatibility table in the below kb article. 

https://support.sitecore.com/kb?id=kb_article_view&sysparm_article=KB1000576

Post installation of the management services package, your CLI should start working. 

Scenario 2: If the instance that you are configuring CLI for is configured to be on http protocol. 

The CLI requires your instance to be https with a valid SSL certificate instaled in it. 

Ref the below article for the steps on how to get a Self Signed SSL Certificate specific to your domain name, and make them as a trusted certificate.  

Run the below command from your command prompt under the solution folder,

dotnet sitecore login --authority https://<<IdentityServerDomain>> --cm https://<<SitecoreInstanceDomain>> --allow-write true

Post this command, your user.json file content would look like this,