Thursday, June 30, 2022

How to implement search in Sitecore website using Solr index?

1. Read language from context and parse the date 

string _language = Context.Language.Name;

            if (_language.ToLower() == "en")

            {

                CultureInfo jaJP = new CultureInfo("ar-QA");

                DateTime dtiDate = new DateTime();

                if (DateTime.TryParseExact(Date.ToString(), "dd/MM/yyyy", jaJP, DateTimeStyles.None, out dtiDate))

                {

                    Date = dtiDate.ToLocalTime();

                }

            }

            ItemManagement itemManagement = new ItemManagement(new SitecoreService(Sitecore.Context.Database));

            Item ItemPeriod = itemManagement.SitecoreService.GetItem<Item>(new Guid(Constants.AppSearchPeriodInfo));


2. Get database from context

            var _db = Context.Database;


3. Get index

            var _index = Sitecore.ContentSearch.ContentSearchManager.GetIndex(string.Format("sitecore_{0}_index", _db.Name.ToLower()));

            var _result = new List<SearchResultItem>();

            DateTime _dateTo = string.IsNullOrEmpty(Date.ToString()) ?

                DateTime.Now.ToUniversalTime().ToLocalTime() : DateTime.Parse(Date.ToString()).AddHours(23).AddMinutes(59).AddSeconds(59).ToUniversalTime().ToLocalTime();

            DateTime _dateFrom = string.IsNullOrEmpty(Date.ToString()) ?

                DateTime.Now.ToUniversalTime().ToLocalTime() : DateTime.Parse(Date.ToString()).ToUniversalTime().ToLocalTime();


4. Specify the template Id for which you want to make a search

            ID _templateId = Constants.PageTemplateID;

            var PgeSize = int.Parse(Sitecore.Configuration.Settings.GetSetting("PgeSize"));

            using (IProviderSearchContext context = _index.CreateSearchContext())

            {

                _result = context.GetQueryable<SearchResultItem>()

                   .Where(x => x.TemplateId == _templateId

                   && x.Language == _language)

                      .Where(x => ((DateTime)x[(ObjectIndexerKey)"date_tdt"]).Between(_dateFrom, _dateTo, Inclusion.Both))

                      .OrderByDescending(x => x["date_tdt"]).Skip((PageNo - 1) * PgeSize).Take(PgeSize).ToList();

            }

            return NewsBullitenArticlesData(_result);


5.  Iterate result received from Sitecore search API

ItemManagement itemManagement = new ItemManagement(new SitecoreService(Sitecore.Context.Database));


            List<Article > articalList= new List<Article >();

 foreach (var article in result)

            {

Article articleModel  = new Article ();

                        Item ItemNews = itemManagement.SitecoreService.GetItem<Item>(new Guid(article.ItemId.ToString()));


                        if (ItemNews != null && ItemNews.Fields.Count > 8)

                        {

                            DateTime dtiDate = new DateTime();

                            if (DateTime.TryParseExact(GetSiteCoreValue(ItemNews.Fields["Date"]), "yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out dtiDate))

                            {

                                articleModel  .Date = BlogsReFormatDateTimeToTimeAgo(dtiDate);

                            }

                            articleModel  .Date = oNewsBulliten.Date.Contains("00:") ? oNewsBulliten.Date.Replace("00:", "12:") : oNewsBulliten.Date;

                            articleModel  .ItemId = ItemNews.ID.ToString();

                            articleModel  .Title = GetSiteCoreValue(ItemNews.Fields["Main Title"]);

                            articleModel  .Description = GetSiteCoreValue(ItemNews.Fields["Body"]);

                            articleModel .Image= GetSiteCoreValue(ItemNews.Fields["Image"]);

                            var options = LinkManager.GetDefaultUrlOptions();

                            string link = LinkManager.GetItemUrl(ItemNews, options);

                            if (!string.IsNullOrEmpty(link))

                            {

                                articleModel  .URL = Sitecore.Configuration.Settings.GetSetting("QNADomain") + link;

                            }

                            articalList.Add(articleModel);

                        }

}

6. Final object-articalList for view integration

Monday, June 20, 2022

How to cancel/delete pending jobs programmatically in Sitecore Content Hub ?

 

You may consider using the Web Client SDK to delete the pending job. Here is a sample code you may use to query the pending job entity ids in the system and delete the jobs. You may include your custom code to filter the jobs you want to delete.


var query = Query.CreateQuery(entities => from e in entities
                                          where e.DefinitionName == "M.Job"
                                          select e);

var scroller = MClient.Querying.CreateEntityScroller(query, TimeSpan.FromSeconds(200),
 EntityLoadConfiguration.DefaultCultureFull);

if (!scroller.CanMoveNext())
{
    return;
}
await scroller.MoveNextAsync().ConfigureAwait(false);

do
{
    foreach(var entity in scroller.Current.Items)
    {
        try
        {
            //filter the entity to delete (eg. condition=pending, logical unit=xx etc.)
            //await client.Entities.DeleteAsync((long)entity.Id);
        }
        catch (Exception ex)
        {
            Logger.Error(ex, $ "Failed to process job entity: {entity.Id}.
 Error: {ex.Message}");
        }
    }
    if (!scroller.CanMoveNext())
    {
        Logger.Info($ "Scroller cannot move next, stopping update.");
        break;
    }
}
while (await scroller.MoveNextAsync().ConfigureAwait(false));


For more details on Web Client SDK:
https://docs.stylelabs.com/contenthub/4.1.x/content/integrations/web-sdk/index.html
https://docs.stylelabs.com/contenthub/4.1.x/content/integrations/sdk-common-documentation/clients/entities-client.html
https://docs.stylelabs.com/contenthub/4.1.x/content/integrations/sdk-common-documentation/clients/querying-client.html

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...