Monday, November 11, 2024

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally while maintaining control over access. Start by authenticating your API request using your credentials to gain access to the necessary endpoints. Once authenticated, you can use the API to create a public link for specific assets or content items by sending a POST request to the designated endpoint, typically `/api/links`. In your request body, include parameters such as the asset ID, link type, and any additional metadata you want to associate with the link. After the request is processed, the API will return a response containing the generated public link, which you can then distribute as needed. It’s important to configure the permissions and expiration settings appropriately to ensure that the link aligns with your organization's security policies. By following these steps, you can efficiently create and manage public links, facilitating easy access to content while leveraging the robust capabilities of the Sitecore Content Hub REST API.  

In this blog, we will walk through how to create public links for assets, how to retrieve the public URL, and how to set expiration dates for those links to help you maintain full control over the shared content.

Content Hub allows us to create public links and integrate them with any type of web application/page.

This blog helps you to create public links using REST API.

Step 1: Authenticating and Creating a Public Link for an Asset

The first step in creating a public link is authenticating your API request. Authentication ensures that only authorized users or applications are able to interact with the Sitecore Content Hub's API. Once authenticated, you’ll be able to create a public link for a specific asset or entity.

API Request to Create Public Link

To create a public link for your selected asset, make a POST request to the following API endpoint:

  • URL: {{ChUrl}}/api/entitydefinitions/M.PublicLink/entities
  • Method: POST
  • Headers: Content-Type: application/json
  • Body (Raw JSON format):
json:
{
	"properties": {		
		"Resource": "downloadOriginal"		
	},
	"is_root_taxonomy_item": false,
	"is_path_root": false,
	"inherits_security": true,
	"entitydefinition": {
		"href": "{{ChUrl}}/api/entitydefinitions/M.PublicLink"
	},
	"relations": {
		"AssetToPublicLink": {
			"parents": [
				{
				"href": "{{ChUrl}}/api/entities/{entityid}"
				}
			]
		}
	}
}


Explanation of Parameters:

  • Resource: Defines the specific resource, such as the original download link, that is being shared.
  • is_root_taxonomy_item: Specifies whether the asset is a root taxonomy item.
  • inherits_security: Ensures that security settings (such as user permissions) are inherited by the public link.
  • entitydefinition: Refers to the entity definition for the type of public link.
  • relations: Links the public link to the selected asset using the entity ID.

Replace {{ChUrl}} with your Content Hub URL and {entityid} with the asset's unique entity ID. After sending the POST request, the API will return a successful "201 Created" response code and provide you with an identifier for the newly created public link.

Expected API Response:

If the request is successful, you will receive a response containing the public link's identifier:

{
    "id": 89358,
    "identifier": "iAOnXWcvmk6cQw"
}


Step 2: Retrieve the Public Link URL

Once the public link is created, you can retrieve the actual public URL by using the identifier you obtained in the previous step. This public URL allows you to share the asset with external parties or integrate it into other applications.

API Request to Get the Public Link URL

  • URL: {{ChUrl}}/api/entities/identifier/{identifier}
  • Method: GET

Replace {identifier} with the identifier returned from the previous API request.

Example Response:

The API will return a response with the generated public link for your asset.

{ "id": 89358, "publicLink": "https://yourcontenthuburl.com/publiclink/iAOnXWcvmk6cQw" }

With the public link, you can now easily distribute the content to your intended users or integrate the link into web applications.

Step 3: Set an Expiration Date for the Public Link

One of the key benefits of using the Sitecore Content Hub API to create public links is the ability to control the lifespan of these links. You can set an ExpirationDate to specify when the public link should no longer be valid. This feature helps enhance security by automatically revoking access to shared assets after a set period, reducing the risk of unauthorized access.

Example Request with Expiration Date:

{ "properties": { "Resource": "downloadOriginal", "ExpirationDate": "2021-11-15T10:18:45.220Z" }, "is_root_taxonomy_item": false, "is_path_root": false, "inherits_security": true, "entitydefinition": { "href": "{{ChUrl}}/api/entitydefinitions/M.PublicLink" }, "relations": { "AssetToPublicLink": { "parents": [ { "href": "{{ChUrl}}/api/entities/{entityid}" } ] } } }

  • ExpirationDate: Set this value in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.mmmZ) to define the exact time when the public link should expire.
By specifying an expiration date, you ensure that content access is temporary and controlled. After the expiration date, the link will become invalid, and users will no longer be able to access the content.                    
                        

Importance and Benefits of Creating Public Links

Using public links through the Sitecore Content Hub REST API offers several advantages:

  1. Controlled Sharing: You can share content externally without compromising internal security. The ability to set expiration dates ensures that shared links are only valid for a limited time, reducing the risk of unauthorized access.

  2. Ease of Integration: Public links can be easily integrated into external web applications, client portals, or even marketing campaigns. This allows for seamless content distribution while maintaining centralized control over assets.

  3. Security and Compliance: Setting permissions and using expiration dates for links helps ensure that your organization remains compliant with security policies and regulatory requirements, ensuring only authorized access to sensitive content.

  4. Optimized User Experience: The public link feature enables organizations to share assets with external users or teams without the need for them to log into the Content Hub. This makes content more accessible, enhancing collaboration with external stakeholders and partners.

  5. Improved Workflow Efficiency: Automating the process of generating public links through API requests minimizes manual intervention, making the content sharing process faster and more efficient.

By leveraging Sitecore Content Hub's REST API to create public links, you can efficiently share content with external parties while maintaining strict control over access and security. The ability to set expiration dates further enhances security, ensuring that links are only valid for as long as needed.

Whether you're sharing assets for marketing, collaboration, or external distribution, public links make it easier to manage access and content flow within and outside your organization.

With Sitecore Content Hub, you can combine flexibility, security, and ease of use to enhance the way you manage and distribute content.

                                            Happy learning and sharing your assets securely!

Monday, November 4, 2024

How to Leverage Custom Search Configuration in the Sitecore Content Hub Search API

Using Custom Search Configuration in the Sitecore Content Hub Search API allows you to tailor search functionalities to meet specific business needs. To get started, define your custom search configuration in the Content Hub, where you can specify parameters such as searchable fields, filters, and sorting options. Utilize the Search API to implement these configurations by creating search queries that leverage the defined parameters, ensuring relevant results are prioritized based on your criteria. You can also enhance user experience by integrating faceted search options, allowing users to filter results dynamically based on attributes like content type or tags. Additionally, consider implementing custom ranking algorithms to further refine search results according to your organization's priorities. Testing and iterating on your custom configurations will help you optimize performance and relevance, ensuring that users can efficiently access the content they need. By leveraging Custom Search Configuration, you can significantly improve the search experience within Sitecore Content Hub. 

The Sitecore Content Hub Search API offers a powerful way to customize and fine-tune search functionalities to align with your organization’s unique business requirements. By defining a custom search configuration, you can tailor the search experience to prioritize specific criteria, filter content effectively, and enhance overall search results. In this guide, we'll walk through the process of creating a custom search configuration in Sitecore Content Hub and demonstrate how to integrate it into your search queries.

Why Use Custom Search Configuration?

Customizing your search configuration in Sitecore Content Hub allows you to:

  • Define searchable fields: Select which fields should be included in the search.
  • Apply filters: Narrow down search results based on specific criteria like content type, tags, or categories.
  • Customize sorting options: Control how search results are ranked or sorted according to your organization’s preferences.
  • Enhance user experience: By integrating features like faceted search, users can filter results dynamically based on attributes.
  • Implement custom ranking algorithms: Refine search results based on your business priorities.

By leveraging these capabilities, you can optimize the search functionality in Sitecore Content Hub to ensure that users can quickly and efficiently access relevant content.


Step 1: Creating Custom Search Configuration in Sitecore Content Hub

To begin using custom search configurations, you first need to define the configuration in Sitecore Content Hub. This involves specifying the fields, filters, and sorting options that are most relevant to your content and user base.

Follow the detailed steps in the Sitecore Content Hub Knowledge Base to learn how to create a custom search configuration. This blog will guide you through all necessary steps to get your search configuration up and running.

Once you've completed the setup, you will have a configuration that reflects your search requirements and can be easily implemented within your search queries.

Step 2: Integrating Custom Search Configuration in Your Search Queries

Once your custom search configuration is created, you can begin using it within your search queries to retrieve content that aligns with your predefined search parameters.

To test and implement your custom search configuration, use the following API details:

API Endpoint

  • URL: /api/search
  • Method: POST
  • Content-Type: application/json

Request Body (JSON Example)

{ "configuration_category": "SearchConfiguration", "defaults": "MySearchConfiguration", "name": "MySearchConfiguration", "skip": 0, "take": 10 }

Explanation of Parameters:

  • configuration_category: This specifies the category of the configuration, which is typically "SearchConfiguration".
  • defaults: The name of the default configuration you want to use for your search query.
  • name: The name of the custom search configuration that you've created in Sitecore Content Hub.
  • skip: Specifies the number of records to skip (for pagination purposes).
  • take: Defines how many records to return per query.

This API request will trigger the search functionality based on your custom configuration, returning results that align with the parameters you've set up.

Step 3: Testing and Optimizing Custom Search Configuration

Once your custom search configuration is integrated into the query, it’s crucial to test it to ensure everything is working as expected. Perform queries using different configurations and examine the results:

  • Verify Filters and Sorting: Ensure that content is being filtered and sorted correctly based on your predefined settings.
  • Check Relevance: Ensure that the most relevant results appear first, and refine the configuration if necessary.
  • Evaluate User Experience: If you’ve integrated faceted search, make sure users can easily filter results based on content type or tags.

Iterate on your configuration based on the test results to further optimize search performance and relevance. This helps ensure users can quickly find the content they need, enhancing their overall experience.

The search API return the following result, which reflects the properties mentioned in the search configuration.




By using Custom Search Configuration in the Sitecore Content Hub Search API, you can significantly improve the way content is searched, filtered, and sorted within your organization. This customization empowers you to create a more efficient and relevant search experience for your users, ensuring they can access content quickly and accurately.

With the flexibility to define parameters like searchable fields, filters, and ranking options, as well as the ability to implement faceted search and custom ranking algorithms, Sitecore Content Hub provides a highly configurable search solution. Test and iterate on your configurations regularly to continuously refine the search experience for your users.

Happy learning and optimizing your Sitecore Content Hub search functionalities!

                                                                   Learning never exhaust mind.

Friday, November 1, 2024

Sitecore instance setup : How to remove Solr services from windows?

 Follow the instructions to remove services like Solr, Sitecore running services, and any other services from Windows.

To remove Solr services from a Windows environment, you'll need to follow a series of steps to ensure a clean uninstallation. First, stop the Solr service by opening the Command Prompt as an administrator and executing the command `sc stop solr`, replacing "solr" with the actual name of your Solr service if it differs. Next, you can disable the service by running `sc delete solr`. After stopping and deleting the service, navigate to the installation directory (typically found in `C:\solr` or wherever you installed Solr) and manually delete the folder to remove all files associated with the Solr instance. Finally, check the Windows Registry for any leftover entries by opening the Registry Editor (regedit) and searching for "Solr" or related keys to ensure there are no remnants. Once you’ve completed these steps, restart your computer to finalize the removal process. This will ensure that Solr services are fully uninstalled from your Windows system.

 Download the NSSM tool from google.




        Open the below folder.



          Copy the full path like this.




        Open the Command prompt in admin mode and navigate to the folder mentioned earlier. 


        Copy the Name of the service that you want to remove from the services.




        Give the following command like “nssm remove” after that put the service name that you want to remove(which is copied from the Servies) followed by space.





        Here it will ask for confirmation, click on “Yes”.





        It will remove the service and give a message like below.





                                                         
Learning never exhausts the mind.”
                                                                             Happy learning!


Tuesday, October 29, 2024

Sitecore Content Hub - Best practices


When working with Sitecore Content Hub, adopting best practices can significantly enhance your content management efficiency and overall user experience. First, establish a clear content governance structure to define roles and responsibilities, ensuring that content creation, approval, and publishing processes are streamlined. Utilize consistent metadata tagging to improve content discoverability and organization, enabling users to quickly find relevant assets. Regularly audit and update your content to maintain its relevance and accuracy, and implement a robust version control system to track changes and maintain historical records. Finally, leverage automation features to simplify repetitive tasks, allowing your team to focus on strategic content initiatives. By following these best practices, you can optimize your use of Sitecore Content Hub and drive more impactful content outcomes.

Asset Type and Media Type:

Asset Type is manual assigned value. It triggers CH built-in tasks:

• Trigger Vision

• Trigger AI

• Trigger extract archive

Asset Media is automatically assigned based on file extension. It drives Media

Processing content flow:

• Image

• Vector

• Documents

• Audio

• Video

• Archives


Custom Media Processing:



Links:



Public Link:

• Public: no authentication required.

• Do not depend on Content Hub Portal availability

• Integrated with CDN

• Distributed

• Works on asset level

• Custom URL path

• Can specify expiration (could be cached up to 10 minutes)

• Based on rendition

• Can apply transformation (t)

• Image merging (b)

• Force download (download=true)

• Has version (v)


Gateway Link:

• Authenticated

• Depends on availability MCH

• Predictable format: .../api/gateway/id/thumbnail

• Works on asset level

• Automatically take master file if no rendition is specified

• Depends on access rights of users


Signed Delivery Link:

• Public

• Timebombed (20 min)

• Contain user-info for auditing

• Hash for security reasons. Changes on each request.

• Do not depend on Content Hub Portal availability

• Distributed


Graph Build:

• Avoid performing multiple heavy operations at the same time. Consider doing one heavy

operation at a time.

• If there is a need to perform heavy operations, please consider performing the operation

when the environment is not expected to be heavily used by users and you can afford to

wait for the graph to rebuild.

• For data ingestions, consider uploading data in smaller batches. For example, if you plan to

upload 400K assets, consider uploading it in four batches of 100K assets. This way you can

you can verify the changes more quickly, and the processing resources utilization goes

back to normal earlier after each batch processing.


Trigger/Action/Script:

• Do not use In process trigger if not necessary, e.g. validation script

• Do use Objective and Conditions to limit the trigger conditions

• Break down single complicated trigger conditions to multiple triggers

• Do not create nested trigger conditions

• Use API Call or Service Bus Action to Azure Function for complicated code

logic

• Regular review the triggers and remove the unused ones


Throttling:

• Make sure that a rate limit of 15 calls per second (per API integration user) is respected.

• Use the WebSDK, which has embedded throttling, over the REST API (for which you have to code the

retry mechanism yourself).

• If required, modify the Content Hub WebSDK built-in retry policy. By default, any call returning an

HTTP 429 response is retried nine times. You can modify the RetryCount property of the retry policy as

required.

• Establish a retry after logic when you use the API. Group your requests into batches and take action

when you receive an HTTP 429 response.

• Create dedicated API users for each integration to detect which one is overloading your platform or

generating errors. If you have a sizeable integration (with multiple components), divide it into blocks

and create a dedicated API user per block.


Users & User group policies:

• You should not assign a user to more than ten user groups.

• Avoid create too many rules in a group policy. Do not define duplicate rules and

permissions.

• Keep the number of different renditions limited in media processing to avoid generating

many renditions.

• Provide the fewest standard renditions that fit the most downstream use cases possible,

and leverage public links with transformations as much as possible.

• Do not turn on Image AI or Video AI if they are no in use


                                                        Happy Learning!

Restrict uploading Video and Audio files in Sitecore Media Library based on Mime Type

 Restrict uploading Video and Audio files in Media Library based on Mime Type/Restrict uploading zip file which contains Video and Audio files in Media Library based on Mime Type:

By default, Sitecore allows the user to upload multiple types of files in the media library. This blog will guide you to restrict the content author not to upload specific file types(Ex. audio, video). Please follow the steps to create the custom pipeline processor to apply the restriction from Sitecore UI. 

Create a pipeline processor :

using Sitecore.Configuration;

using Sitecore.Diagnostics;

using Sitecore.Pipelines.Upload;

using Sitecore.Zip;

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.IO;

using System.IO.Compression;

using System.Linq;

using System.Web;

namespace SampleWebsite.Web.Foundation.Pipelines.Pipelines

{

    public class CheckFileTypePipeline : UploadProcessor

    {

        private bool _isAllowed;

        private string _extensions;

        public CheckFileTypePipeline(string blocked)

        {

            if (string.IsNullOrEmpty(blocked))

                return;

            this._isAllowed = false;

            this._extensions = blocked.Replace(" ", "").ToLower();

        }

        public void Process(UploadArgs args)

        {

            Assert.ArgumentNotNull((object)args, nameof(args));

            if (string.IsNullOrEmpty(this._extensions))

                return;

            List<string> stringList = this.PrepareExtensions(this._extensions);

            foreach (string file1 in (NameObjectCollectionBase)args.Files)

            {

                HttpPostedFile file2 = args.Files[file1];

                if (!string.IsNullOrEmpty(file2.FileName))

                {

                    if (UploadProcessor.IsUnpack(args,file2))

                      {

                        ZipReader zipReader = new ZipReader(file2.InputStream);

                        try

                        {

                            foreach (ZipEntry entry in zipReader.Entries)

                            {

                                string mimeTypef = MimeMapping.GetMimeMapping(entry.Name);

                                bool flag = stringList.Any(x => mimeTypef.Contains(x));

                                if ((!this._isAllowed || !flag) && (!this._isAllowed && flag || this._isAllowed && !flag))

                                {                                   

                                HttpContext.Current.Response.Write("<script type=\"text/JavaScript\">alert(\"Uploading files with " + mimeTypef + " as type is restricted\");</script>");

                                   Log.Audit(string.Format("Upload restricted: {0}", (object)entry.Name), (object)this);

                                    new Done().Process(args);

                                   args.AbortPipeline();

                                    return;

                                }

                            }

                        }

                        finally

                        {                           

                            file2.InputStream.Position = 0L;

                        }

                    }

                    string mimeTypef2 = MimeMapping.GetMimeMapping(file2.FileName);

                    bool flag1 = stringList.Any(x => mimeTypef2.Contains(x));

                   if ((!this._isAllowed || !flag1) && (!this._isAllowed && flag1 || this._isAllowed && !flag1))

                        {                           

                        HttpContext.Current.Response.Write("<script type=\"text/JavaScript\">alert(\"Uploading files with " + mimeTypef2 + " as file type is restricted\");</script>");

                            Log.Audit(string.Format("Upload restricted: {0}", (object)file2.FileName), (object)this);

                            new Done().Process(args);                           

                            args.AbortPipeline();

                            break;

                        }

                    }

            }

        }

        private List<string> PrepareExtensions(string csvExtensions)

        {

            string[] strArray = csvExtensions.Split(',');

            List<string> stringList = new List<string>();

            foreach (string str in strArray)

                stringList.Add(str);

            return stringList;

        }

    }

}


Create a patch Config file :

<?xml version="1.0" encoding="utf-8"?>

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

  <sitecore>

    <processors>

      <uiUpload>

        <processor mode="on" type=" SmpleSite.Web.Foundation.Pipelines.Pipelines.CheckFileType, SmpleSite.Web.Foundation.Pipelines" patch:before="*[1]">

          <param desc="Blocked filetypes (comma separated)">video,audio</param>

        </processor>

      </uiUpload>

    </processors>

  </sitecore>

</configuration>


Let's deploy these files to the website's root folder and give it a try.

 Go to Media library and try to upload a file and then click on “Choose File”.


Click on Upload




Final result: You see a restriction message on the pop-up.



                        
                                                            Happy learning!

How to Create a Public Link Using the Sitecore Content Hub REST API

Creating a public link using the Sitecore Content Hub REST API is a straightforward process that enables you to share content externally whi...