Click here to Skip to main content
14,693,599 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public List<Item> GetTaggedRelatedItems()
            List<Item> taggedRelatedItem = new List<Item>();
                const int totalItemCount = 4;
                var scContext = new SitecoreContext();
                List<Item> finalItems = new List<Item>();
                //Fetching the pubs and reports landing page from rendering para

                var topicField = Sitecore.Context.Item.Fields["Topic"];

                if (topicField != null)
                    string[] housingPhaseTags = topicField.Value.Split(new char[] { '|' });
                    foreach (var tag in housingPhaseTags)

                        // Check for tags which are added as |Tag1|Tag2 instead of Tag1|Tag2
                        if (!string.IsNullOrWhiteSpace(tag))
                            var tagItem = Sitecore.Context.Database.GetItem(ID.Parse(tag));
                            if (tagItem != null && tagItem.Fields["RootNode"] != null)
                                var rootNode = Sitecore.Context.Database.GetItem(ID.Parse(tagItem.Fields["RootNode"].Value));
                                if (rootNode != null)
                                    //var relatedItems = rootNode.Axes.GetDescendants().Where(x => x.Visualization.GetLayout(Sitecore.Context.Device) != null);

                                    var childItems = contentSearchAPI.GetIndexForRootItem(rootNode, ID.Parse(Guid.Empty));
                                    if (childItems != null)
                                        var relatedItems = childItems.Where(x => x != null && x.Visualization.GetLayout(Sitecore.Context.Device) != null); //## Content Search API ##

                                        var housingPhaseItems = relatedItems.Where(x => x.Fields["Topic"].Value.Contains(tag)).ToList();


                                        //Fetch the topic or subject tag in the given navigational bucket
                                        var topicTags = Context.Item.Fields["Tags"];
                                        if (topicTags != null && !string.IsNullOrWhiteSpace(topicTags.Value))
                                            //Hack to make the tags work as the content migration script introduced extra | at the begining of the tags field.
                                            // So picking the [1] item as opposed [0] item.
                                            var firstTopicTag = topicTags.Value.Split(new char[] { '|' })[1];
                                            finalItems = housingPhaseItems.Where(x => x.Fields["Tags"].Value.Contains(firstTopicTag)).ToList();

                                            // Fetch remaining values from other topic or subject tags
                                            if (finalItems.Count == 0 || finalItems.Count < 4)
                                                finalItems.AddRange(GetSecondaryRelatedItem(housingPhaseItems, totalItemCount - finalItems.Count));

                                            finalItems.ForEach(x => taggedRelatedItem.Add(scContext.Cast<Item>(x)));
                                        Sitecore.Diagnostics.Log.Info("HCWebHelper -> GetTaggedRelatedItems - No Items(s) found from Index", this);

            catch (Exception ex)
                StackTrace stackTrace = new StackTrace(ex, true);
                var topFrame = stackTrace.GetFrame(1);
                var caller = topFrame != null ? topFrame.GetMethod()?.Name : string.Empty;
                var line = topFrame != null ? topFrame.GetFileLineNumber().ToString() : string.Empty;

                var exString = string.Format(@"Message : {0}, Caller: {1}, Line: {2}, StackTrace: {3}", ex.Message, caller, line, ex.StackTrace);

                Sitecore.Diagnostics.Log.Error(exString, this);
            //Incase of empty taggedRelatedItem list it should return empty list<item>()  
            return (taggedRelatedItem != null && taggedRelatedItem.Count >= 4) ? taggedRelatedItem.Take(4).ToList() : new List<Item>();

What I have tried:

My code is as shown but i am getting log error "Index was outside the bound of the array"
Updated 13-Oct-20 0:41am

So use your logged information to identify where the problem is - it tells you the line and method, so it should be possible to identify where exactly in you code the problem is.

With that, you can look for the array element access, and either log the actual size of the collection and the index you are using, or use the debugger to find out what those values are.

With that information, you can start looking at why it's a problem - but we can't do any of that for you - we have no access to your running code or to your data!
Potentially, the problem is at line:
var firstTopicTag = topicTags.Value.Split(new char[] { '|' })[1];

You are expecting an array length of two post splitting and directly accessing the second value. Seems, post split, there is no value at that index and thus the error.

Please handle it.

Going forward, would strongly recommend to use Visual Studio debugger step-wise to see where from the error is raised - most of the times, you will be able to figure yourself on what could be going wrong.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900