• Not Answered

The given key was not present in the dictionary

Upgrading from 8.2 to 9.1.  The following code works in 8.2 but fails in 9.1

 

 

using System;
using System.Linq;
using CCO.Foundation.Assets;
using CCO.Foundation.Assets.Services.Implementations;
using CCO.Foundation.Assets.Services.Interfaces;
using CCO.Foundation.BaseTemplates;
using CCO.Foundation.SitecoreExtensions.Wrappers;
using Glass.Mapper.Sc;
using Jabberwocky.Glass.Models;
using Jabberwocky.Glass.Services;
using Sitecore.Data.Events;
using Sitecore.Data.Items;
using Sitecore.Events;
using Sitecore.SecurityModel;

namespace CCO.Feature.Activities.Events.ItemCreated
{
/// <summary>
/// This pipeline updates the pre disclosure and post disclosure override text
/// on focus nodes to match the parent program's node
/// </summary>
public class SelectBoilerplateTextEventHandler
{
    private readonly ISitecoreService _sitecoreService;
    private readonly IItemService _itemService;
    private readonly ISitecoreLogger _sitecoreLogger;
    private readonly IAssetService _assetService;

    public SelectBoilerplateTextEventHandler()
    {
        //sitecore does not DI these event handlers
        //manually creating dependencies in ctor called by sitecore
        _sitecoreService = new SitecoreService("master");
        _sitecoreLogger = new SitecoreLogger();
        _itemService = new ItemService(_sitecoreService);
        var contextWrapper = new SitecoreContextWrapper();
        _assetService = new AssetService(contextWrapper);
    }


    public SelectBoilerplateTextEventHandler(ISitecoreService sitecoreService, IItemService itemService, ISitecoreLogger sitecoreLogger, IAssetService assetService)
    {
        _sitecoreService = sitecoreService ?? throw new ArgumentNullException(nameof(sitecoreService));
        _itemService = itemService ?? throw new ArgumentNullException(nameof(itemService));
        _sitecoreLogger = sitecoreLogger ?? throw new ArgumentNullException(nameof(sitecoreLogger));
        _assetService = assetService ?? throw new ArgumentNullException(nameof(assetService));
    }


    protected void ItemCreated(object sender, EventArgs args)
    {
        var itemArgs = Event.ExtractParameter(args, 0) as ItemCreatedEventArgs;

        var createdItem = itemArgs?.Item;
        //check for nulls
        if (createdItem == null)
            return;
        //check to see if item is focus node
        if (createdItem.TemplateID != IFocusConstants.TemplateId)
            return;

        UpdateBoilerPlateText(createdItem);
    }

    private void UpdateBoilerPlateText(Item focusNode)
    {
        try
        {
            var parentProgramProvider = GetParentProgramProvider(focusNode);

            using (new EditContext(focusNode))
            using (new SecurityDisabler())
            {
                focusNode[IFocusConstants.PostDisclosureFieldId] = parentProgramProvider?.Default_Postdisclosure_Text?._Id.ToString("B").ToUpper();
                focusNode[IFocusConstants.PreDisclosureFieldId] = parentProgramProvider?.Default_Predisclosure_Text?._Id.ToString("B").ToUpper();
            }
        }
        catch (Exception ex)
        {
            _sitecoreLogger.Error("Unable to select boilerplate text for focus node", ex);
        }

    }

    private IGlobal_Provider GetParentProgramProvider(Item focusNode)
    {
         var parent = _sitecoreService.GetItem<IGlassBase>(focusNode.Parent.ID.Guid);
         if (parent is I_Program_Page_Base parentProgram)
         {
             return GetMainProvider(parentProgram);
         }
         var parentprogram = _itemService.GetAncestors(parent)?
             .OfType<I_Program_Page_Base>()
             .FirstOrDefault();
         return GetMainProvider(parentprogram);
    }

    private IGlobal_Provider GetMainProvider(I_Program_Page_Base programPage)
    {
        var provider = _assetService.GetProviders(programPage)
            .FirstOrDefault()?.CME_Provider;

        return provider;
    }
  }
}

Returns the following error when being run in 9.1:

Server Error in '/' Application.


The given key was not present in the dictionary.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.

Source Error: 

Line 32:             //sitecore does not DI these event handlers
Line 33:             //manually creating dependencies in ctor called by sitecore
Line 34:             _sitecoreService = new SitecoreService("master");
Line 35:             _sitecoreLogger = new SitecoreLogger();
Line 36:             _itemService = new ItemService(_sitecoreService);


Source File: D:\Source\CCO_Website\src\Feature\Activities\code\Events\ItemCreated\SelectBoilerplateTextEventHandler.cs    Line: 34 

Stack Trace: 

[KeyNotFoundException: The given key was not present in the dictionary.]
   System.ThrowHelper.ThrowKeyNotFoundException() +36
   System.Collections.Generic.Dictionary`2.get_Item(TKey key) +52
   Glass.Mapper.Sc.SitecoreService..ctor(String databaseName, String contextName) +67
   CCO.Feature.Activities.Events.ItemCreated.SelectBoilerplateTextEventHandler..ctor() in D:\Source\CCO_Website\src\Feature\Activities\code\Events\ItemCreated\SelectBoilerplateTextEventHandler.cs:34

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +289
   Sitecore.Reflection.ReflectionUtil.CreateObject(Type type, Object[] parameters) +119
   Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert) +108
   Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +163
   Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, Boolean assert) +68
   Sitecore.Events.EventSubscribers.Add(String eventName, XmlNode configNode) +556
   Sitecore.Events.Event.BuildConfigSubscribersFromConfiguration() +344
   Sitecore.DependencyInjection.LazyResetable`1.get_Value() +150
   Sitecore.Events.Event.RaiseEvent(String eventName, Object[] parameters) +389
   Sitecore.ContentSearch.Maintenance.IndexDatabasePropertyStore.Get(String key) +205
   Sitecore.ContentSearch.SolrProvider.SolrIndexSummary.get_LastUpdatedTimestamp() +82
   Sitecore.ContentSearch.Maintenance.Strategies.BaseAsynchronousStrategy.LogStrategyInitialization(ISearchIndex index) +94
   Sitecore.ContentSearch.Maintenance.Strategies.BaseAsynchronousStrategy.Initialize(ISearchIndex searchIndex) +83
   Sitecore.ContentSearch.Maintenance.Strategies.IntervalAsynchronousStrategy.Initialize(ISearchIndex searchIndex) +18
   Sitecore.ContentSearch.TypeActionHelper.Call(Action`1 action, IEnumerable`1 instances) +197
   Sitecore.ContentSearch.SolrProvider.SolrSearchIndex.Initialize() +180
   Sitecore.ContentSearch.SolrProvider.SolrContentSearchManager.Initialize() +169
   (Object , Object ) +9
   Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +484
   Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) +236
   Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
   Sitecore.Nexus.Web.HttpModule.Application_Start() +215
   Sitecore.Nexus.Web.HttpModule.Init(HttpApplication app) +1184
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +581
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +277
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +714

 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0