Hot to Mock a DbQuery used in a join - unit-testing

I am using a View in EntityFramework Core through something like
modelBuilder.Query<DeviceHierarchy>().ToView("DeviceHierarchy");
I tried to use the solution from this question to mock the view.
The view is used in a join like this
Context.Devices.Where(...).Join(Context.DeviceHierarchy, ...)
but I got an exception and can not figure out what's the problem
at System.Linq.Lookup`2.CreateForJoin(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.JoinIterator[TOuter,TInner,TKey,TResult](IEnumerable`1 outer, IEnumerable`1 inner, Func`2 outerKeySelector, Func`2 innerKeySelector, Func`3 resultSelector, IEqualityComparer`1 comparer)+MoveNext()
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Max(IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.AsyncEnumerable.AsyncEnumerableAdapter`1.MoveNextCore(CancellationToken cancellationToken)
at System.Linq.AsyncEnumerable.AsyncIterator`1.MoveNext(CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult](QueryContext queryContext, Func`2 compiledQuery, IDiagnosticsLogger`1 logger, Type contextType)
Can a view be mocked using Microsoft.EntityFrameworkCore.InMemory package?

Related

Sitecore Commerce Business Tools doesn't load

I'm facing a problem with loading the Sitecore Commerce Business Tools on my local machine. I don't get any error in my browser which you can check on the following screenshoot, but the page is not initialized:
Seems like the operations GetNavigationView() and GetLanguageView() are stuck on getting data, but I couldn't figure out what could be the problem.
As preparation steps, I did the Sitecore Commerce Bootstrap, and Environment Initialization via Postman and everything went ok.
In the CommerceAuthoring_Sc9\wwwroot\config.json I set up the certificate thumbprint and here is what I have in the AppSettings:
"AppSettings": {
...
"SitecoreIdentityServerUrl": "https://localhost:5050",
"AllowedOrigins": [
"https://localhost:4200",
"https://sxa.storefront.com"],
"AntiForgeryEnabled": false,
"UseHttpsInKestrel": true,
"SslPort": 5000,
"SslPfxPath": "wwwroot/localhost.pfx",
"SslPfxPassword": "sitecore"
}
Also in the CommerceAuthoring_Sc9\wwwroot\bootstrap\Global.json I added all the environments I use.
Here you can check some of the errors I noticed in the CommerceAuthoring logs:
ERROR ImportMinion Error Access to the path 'C:\Import.lock' is denied. Inner
...
ERROR SitecoreConnectionManager.Error: Message=Invalid URI: The hostname could not be parsed.|Trace=
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel) System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest( CommerceContext commerceContext, String action, String method, ItemModel itemModel)
...
ERROR SitecoreConnectionManager.Error: Message=One or more errors occurred.|Trace= at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel)
System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel)
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---
...
ERROR Management.block.getitemsbypath: Sitecore Item Service Get item failed, Item /sitecore/Commerce/Commerce Control Panel/Commerce Engine Settings/Commerce Terms/BusinessTools/ViewNames not found.
I checked some solutions that were already mentioned across the forums but no luck fo far.
I'll very appreciate if you have any advice for me!
Updated
After some time, we got the following error on the UAT env. but I'm not sure if we can do a Commerce Bootstrap there without losing our data:
INFO Management.block.getitembypath./sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront|en
INFO Management.block.getitembypath./sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront: Language=en
ERROR SitecoreConnectionManager.Error: Message=Unexpected character encountered while parsing value: <. Path '', line 0, position 0.|Trace= at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.GetItemByPath(CommerceContext commerceContext, String path, String language)
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.GetItemByPath(CommerceContext commerceContext, String path, String language)
ERROR Management.block.getitembypath: Sitecore Item Service Get item failed, Item /sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront not found.
ERROR CtxMsg.Error.InvalidShop: Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR PipelineAbort:Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR CtxMsg.Error.InvalidShop: Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR CommerceController.OnActionExecuting.BadRequest: Code=Error|TermKey=InvalidShop|Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
Also, the storefront item 'CommerceEngineDefaultStorefront' exist in the database that is specified in the PlugIn.Content.PolicySet-1.0.0.json file. I feel some of the json files has invalid params/values or the formatting is wrong, but I couldn't find any lead, furthermore, they haven't been changed recently.
Answer
Eventualy, it appeared the our CD was down for some period.

sitecore 8 - getting "Failed" JS dialog when clicking on treeview links

When I tried to click on the treeview links from "Insert Options" (and in other windows as well).
Please check this below link for the error screen shot.
Error on tree-view link click
The error log has the following details:
*
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.sitecore_shell_controls_treeviewex_treeviewex_aspx.ProcessRequest(HttpContext context) in c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\252d77a1\7452ed5e\App_Web_0so42fby.0.cs:line 0
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.ArgumentNullException
Message: Null ids are not allowed.
Parameter name: name
Source: Sitecore.Kernel
at Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(String argument, String argumentName)
at Sitecore.Web.UI.HtmlControls.Data.DataViewFactory.GetDataView(String name, String parameters)
at Sitecore.Web.UI.WebControls.TreeviewEx.RenderChildren(HtmlTextWriter output, Item parent)
at Sitecore.Web.UI.WebControls.TreeviewEx.Render(HtmlTextWriter output)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Page.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
*
Kindly help me if anyone knows the reason for this issue? I tried with one solution found in one of the site (by "disable" the authentication in the IIS) but it did not work for me.
Thanks in advance for your help.
I stumbled upon your question since we have the same problem, and this article describes exactly what we did and what problem we ran into.
I don't know if you added a URL rewrite rule for SEO to always use lowercase URLs, but it seems that Sitecore isn't a fan. So you should exclude this rule for your CM environment (what we did) or specifically exclude Sitecore urls (what they describe in the article).

Sitecore: Value cannot be null. Parameter name: uri

Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: uri
Source: Sitecore.Kernel
I was editing a placeholder item in a local
Sitecore 8.1 (rev. 151207) instance when I got this error. Now I can't edit, delete, or reset it (or its parent folders). I also can't read the item in the content editor as the error pops up when I click on the parent folder. I've tried deleting/editing it and it's parent folder from the content editor, through code, and through PowerShell commands but the same error always shows.
I've also tried replacing my configs and bin folders with my backup copies, clearing cache, restarting IIS and the app pool, but nothing has helped.
I'm completely stuck. Does anyone know how to fix this?
Edit:
The full error in the logs is:
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: uri
Source: Sitecore.Kernel
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Data.ItemUri..ctor(ItemUri uri)
at Sitecore.Data.Items.Item.GetItemUriFromSourceItem()
at Sitecore.Data.Items.Item.get_SourceUri()
at Sitecore.Data.Items.Item.get_Source()
at Sitecore.Data.Fields.Field.GetSourceItem()
at Sitecore.Data.Fields.Field.GetInheritedValue(Boolean allowStandardValue)
at Sitecore.Pipelines.GetFieldValue.GetInheritedValue.Process(GetFieldValueArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Data.Fields.Field.GetValue(Boolean allowStandardValue, Boolean allowDefaultValue, Boolean allowFallbackValue, Boolean allowInheritValue, Boolean allowInnerValue)
at Sitecore.Pipelines.ItemProvider.GetItem.GetLanguageFallbackItem.IsItemFallbackEnabled(Item item)
at Sitecore.Pipelines.ItemProvider.GetItem.GetLanguageFallbackItem.Process(GetItemArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
at Sitecore.Data.Managers.ItemManager.GetItem(ID itemId, Language language, Version version, Database database, SecurityCheck securityCheck)
at Sitecore.Nexus.Data.DataCommands.GetChildrenCommand.Execute(Item )
at Sitecore.Data.Engines.EngineCommand`2.Execute()
at Sitecore.Data.Managers.ItemProvider.GetChildren(Item item, ChildListOptions options)
at Sitecore.Data.Managers.ItemProvider.GetChildren(Item item, SecurityCheck securityCheck, ChildListOptions options)
at Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
at Sitecore.Data.Managers.PipelineBasedItemProvider.GetChildren(Item item, SecurityCheck securityCheck)
at Sitecore.Collections.ChildList.Populate(ChildListOptions options)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(Item item, Boolean processChildren)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(Item item, Boolean processChildren)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(List`1 items)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetCheckCloneLinksMessage(List`1 items)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.CheckCloneLinks(ClientPipelineArgs args)
The exception you provided occurs because you have nonempty invalid value in the __Source Item - {19B597D3-2EDD-4AE2-AEFE-4A94C7F10E31} field in your item. __Source Item is responsible for storing the original item URI for the clone items.
I don't know how you achieved that because there is a processor ValidateCloneSourceModifications in the saveItem pipeline that prevents of saving items with invalid __Source Item field.
I was able to reproduce your exception by changing the field value in the DB.
How to fix:
Find you broken field in the master DB -> SharedFields table. The FieldId is '19B597D3-2EDD-4AE2-AEFE-4A94C7F10E31'.
Fix it. It should be something like sitecore://master/{AE76A034-9491-4B83-99F5-39F227D6FB59}, where the ID is the original item id. You could also just set '' as a value, but it will remove the binding to the original item.
Clear cache.
It must help.
You can try the DB Browser /sitecore/admin/dbbrowser.aspx with this tool you can also delete items.
If this DB Browser admin tools fail, then I'm curious what's in the master database, check directly in sql what make this item special is than an option.

Sitecore 8: Getting application error when removing broken links

I try to remove broken links on my master database using the tool provided by the following url.
http://mysite/sitecore/admin/RemoveBrokenLinks.aspx
After some time the process being interrupted and I got the following error on Sitecore log.
6220 10:56:26 INFO Removing broken link- Database: master, Item: /sitecore/content/Home/blog/2012/January/13/totaljobs-group-benefit-from-expert-sitecore-consultancy-delivered-by-codehouse, Field: __Renderings, Target item database: master, Target item path: /sitecore/content/global/Codehouse Widgets/Mini Form Widgets/newsletter-subscription
6220 10:56:26 INFO Done
6220 10:56:26 INFO Removing broken link- Database: master, Item: /sitecore/content/Home/blog/2012/January/13/totaljobs-group-benefit-from-expert-sitecore-consultancy-delivered-by-codehouse, Field: __Renderings, Target item database: master, Target item path: /sitecore/content/global/Codehouse Widgets/Mini Form Widgets/sitecore-demo-text-only
6220 10:56:26 INFO Done
6220 10:56:26 ERROR Error looking up template field. Field id: {00000000-0000-0000-0000-000000000000}. Template id: {0437FEE2-44C9-46A6-ABE9-28858D9FEE8C}
Exception: System.ArgumentOutOfRangeException
Message: Null ID is not allowed.
Parameter name: fieldID.
Actual value was {00000000-0000-0000-0000-000000000000}.
Source: Sitecore.Kernel
at Sitecore.Data.Templates.TemplateSection.GetField(ID fieldID)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.GetField(ID fieldID)
6220 10:56:26 ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.ArgumentOutOfRangeException
Message: Null ID is not allowed.
Parameter name: fieldID.
Actual value was {00000000-0000-0000-0000-000000000000}.
Source: Sitecore.Kernel
at Sitecore.Data.Templates.TemplateSection.GetField(ID fieldID)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.GetField(ID fieldID)
at Sitecore.Data.Fields.Field.GetTemplateField()
at Sitecore.Data.Fields.FieldTypeManager.GetField(Field field, String runtimeValue)
at Sitecore.sitecore.admin.RemoveBrokenLinks.FixBrokenLinksInDatabase(Database database, Boolean serializeItem)
at Sitecore.sitecore.admin.RemoveBrokenLinks.FixBrokenLinksOnClick(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Can you made a cleanup database before doing RemoveBrokenLinks?
Tu clean up database go to ->Control Panel->Database->Clean up Database
I guess you have some orphaned items (items without templates)
When you are doing a Cleanup Database next tasks are executed:
Removes items that have parents, but the parents are not in the item
tree.
Removes invalid language data.
Removes fields for non existing items.
Removes orphaned items.
Removes unused blob records.
Removes fields from orphaned items removed in step 4.
Rebuilds the Descendants table (which stores parent/child relationships).
Clears all caches.
It's quite odd that it didn't resolve the issue by using Clean up Database or by Rebuilding the link database.
Few questions:
During the clean up and rebuilding process, did you find any
relevant entry related to the issue in your Sitecore log? If yes, could you please paste it here, as well.
Reading the stack traces you provided, it looks like that there is/are orphaned template(s) and that's the reason why it throws an Exception: System.ArgumentOutOfRangeException. Could you please repeat the same rebuild and clean up process, and let us know the result of the 2nd run?
Alternatively, if you find repeating the process a very time consuming and performance heavy then you might want to consider creating a LinkDatabaseRefreshTool.aspx file, put it inside the \Website\admin folder with the following code as your processor:
foreach (var specificItem in itemList)
{
specificItem.Editing.BeginEdit();
Sitecore.Globals.LinkDatabase.UpdateReferences(specificItem);
specificItem.Editing.EndEdit();
}
Create an asp:Textbox and a submit button that invokes this method OnClick. Open the tool by accessing the http:\\YOUR_WEBSITE\admin\LinkDatabaseRefreshTool.aspx
I experienced the same issue before, and I just rebuild it again and that resolved the issue. Maybe just the same solution on your end, still worth a try.

Server Error "Object reference not set to an instance of an object" after insert from branch

Everything works correctly but after Sitecore update from 7.0 to 7.2 I see the following Server Error when creating a site from a branch
[NullReferenceException: Object reference not set to an instance of an object.]
Sitecore.Nexus.Data.DataCommands.AddFromTemplateCommand.(Item , Item , String , ID , ID , String , SafeDictionary`2 ) +420
Sitecore.Nexus.Data.DataCommands.AddFromTemplateCommand.(Item , Item , String , ID , ID , String , SafeDictionary`2 ) +856
Sitecore.Nexus.Data.DataCommands.AddFromTemplateCommand.(String , Item , Item , ID ) +569
Sitecore.Data.Engines.DataCommands.AddFromTemplateCommand.DoExecute() +113
Sitecore.Data.Engines.EngineCommand`2.Execute() +121
Sitecore.Data.Engines.DataEngine.AddFromTemplate(String itemName, ID templateId, Item destination, ID newId) +101
Sitecore.Data.Managers.ItemProvider.AddFromTemplate(String itemName, ID templateId, Item destination, ID newId) +363
Sitecore.Data.Managers.ItemManager.AddFromTemplate(String itemName, ID templateId, Item destination, ID newItemId) +203
Sitecore.Data.Managers.ItemManager.AddFromTemplate(String itemName, ID templateId, Item destination) +286
Sitecore.Data.Items.Item.Add(String name, BranchId branchId) +110
Sitecore.Workflows.WorkflowContext.AddItem(String name, BranchItem branch, Item parent) +279
Sitecore.Shell.Framework.Commands.AddMaster.Add(ClientPipelineArgs args) +803
[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.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
Sitecore.Nexus.Pipelines.NexusPipelineApi.Resume(PipelineArgs args, Pipeline pipeline) +398
Sitecore.Web.UI.Sheer.ClientPage.ResumePipeline() +285
Sitecore.Web.UI.Sheer.ClientPage.OnPreRender(EventArgs e) +547
Sitecore.Shell.Applications.ContentManager.ContentEditorPage.OnPreRender(EventArgs e) +25
System.Web.UI.Control.PreRenderRecursiveInternal() +113
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4297
A site creates correctly and I see no problems there.
As far as I see the error occurs in the item:addmaster command:
<command name="item:addmaster" type="Sitecore.Shell.Framework.Commands.AddMaster,Sitecore.Kernel" />
I have tried to decompile Sitecore.Nexus library but without any success. After some of hours of the investigation I found that the error disappears if turn off a custom event handler
<event name="item:created">
<handler type="App.Client.Tasks.ItemEventHandler, App.Client" method="OnItemCreated" />
</event>
The handler is responsible for auto mapping configuration settings in a new site created from a branch. Technically there is an item in branch template called Mapper and it works as a trigger. It is the last item in the branch tree. So when an admin adds a site from a branch, event handler checks that the Mapper is created (in other words a site is created), runs auto mapping functionality and deletes the trigger.
If to omit all checks, the handler looks like
new ItemMappingManager(contextItem, Database.GetDatabase("master").Items[ID.Parse(MappingConfigurationItemId)]).Execute();
// delete the trigger item once the branch has been created and mapping is done
using (new SecurityDisabler())
{
contextItem.Delete();
}
Looks like something changed in the Sitecore's event model but I have a lack of knowledge here.
Try wrapping any calls to Sitecore.Data.Engines.DataEngine.AddFromTemplate or any calls that you are making that add an item with an EventDisabler. Because the exception is being thrown in Nexus, it's difficult to say what the exact cause of the issue is.
When I experienced a similar issue, I had a theory that there may have been some eventing that was firing and causing the exceptions. The error did not always occur, and it was difficult to find the cause of the error since it was being thrown in Nexus. While investigating and debugging as best I could (deobfuscated, decompiled and read through and debugged into Nexus), I found that there were several API calls being made that raise events (e.g. AddVersion, AddMaster, etc.). I considered my theory confirmed when the exception disappeared after I wrapped my code in an EventDisabler.
My Similar Experience
I just experienced nearly the same issue with Sitecore 8.1.2. The difference between my code and the code in the OP is that I am leveraging the new (I believe newer than the OP) ItemProvider via a processor that I have added to the AddFromTemplate pipeline.
The below is the processor that I added. I use this processor to run rules, and I was receiving the exact same error, until I wrapped my call to Sitecore.Data.Engines.DataEngine.AddFromTemplate (must be called or else the item never actually gets created) in an EventDisabler.
Processor Before Fix
public override void Process([NotNull] AddFromTemplateArgs args)
{
ID id;
if (args.Aborted
|| string.IsNullOrWhiteSpace(RuleFolderId)
|| !Settings.Rules.ItemEventHandlers.RulesSupported(args.Destination.Database)
|| !ID.TryParse(RuleFolderId, out id))
{
return;
}
Assert.HasAccess(args.Destination.Access.CanCreate(), "You do not have permission to create items here.");
// exception thrown from this call, which is a required call for this
// processor, or else the item will not actually be created
var item = args.Destination.Database.Engines.DataEngine.AddFromTemplate(
args.ItemName,
args.TemplateId,
args.Destination,
args.NewId);
args.ProcessorItem = item;
args.Result = item;
var ruleContext = new PipelineArgsRuleContext<AddFromTemplateArgs>(args);
RuleManager.RunRules(ruleContext, id);
}
Processor with fix
public override void Process([NotNull] AddFromTemplateArgs args)
{
ID id;
if (args.Aborted
|| string.IsNullOrWhiteSpace(RuleFolderId)
|| !Settings.Rules.ItemEventHandlers.RulesSupported(args.Destination.Database)
|| !ID.TryParse(RuleFolderId, out id))
{
return;
}
Assert.HasAccess(args.Destination.Access.CanCreate(), "You do not have permission to create items here.");
using (new EventDisabler()) // fixes the exception from nexus
{
var item = args.Destination.Database.Engines.DataEngine.AddFromTemplate(
args.ItemName,
args.TemplateId,
args.Destination,
args.NewId);
args.ProcessorItem = item;
args.Result = item;
}
var ruleContext = new PipelineArgsRuleContext<AddFromTemplateArgs>(args);
RuleManager.RunRules(ruleContext, id);
}
Additional Observations
The error was only experienced about 33% of the time and only when adding an item from a branch template programmatically (never occurred when adding from the UI). The exact location of the error also appeared to change each time, and I was not able to find the source of this randomization.