question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

V8: Can't Save and Publish Content during startup due to notifications issue

See original GitHub issue

I’m attempting to create content, then save and publish using the content service but I’m running in to a null reference exception.

I’m not sure why this is happening, my hunch at the moment it is that I’m trying to create it from a composer and wondering if maybe something isn’t initialised for me at that point.

Anyway, here’s the code I’m using (or at least, the important parts):

using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Models;

namespace Test
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class ContentComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Components().Append<ContentComponent>();
        }
    }

    public class ContentComponent : IComponent
    {
        public void Initialize()
        {
            IContent homepageNode = Current.Services.ContentService.GetRootContent().FirstOrDefault(x => x.ContentType.Alias == "homepage");

            if (homepageNode == null)
            {
                IContent homepage = Current.Services.ContentService.Create("Homepage", -1, "homepage");

                Current.Services.ContentService.SaveAndPublish(homepage);
            }
        }

        public void Terminate() { }
    }
}

When I attempt to do this, I get the following error:

Object reference not set to an instance of an object.

And the stack trace:

   at Umbraco.Web.Routing.RedirectTrackingComponent.get_Moving()
   at Umbraco.Web.Routing.RedirectTrackingComponent.get_LockedEvents()
   at Umbraco.Web.Routing.RedirectTrackingComponent.ContentService_Publishing(IContentService sender, PublishEventArgs`1 args)
   at Umbraco.Core.Events.QueuingEventDispatcherBase.DispatchCancelable[TSender,TArgs](TypedEventHandler`2 eventHandler, TSender sender, TArgs args, String eventName)
   at Umbraco.Core.Services.Implement.ContentService.StrategyCanPublish(IScope scope, IContent content, Boolean checkPath, IReadOnlyList`1 culturesPublishing, IReadOnlyCollection`1 culturesUnpublishing, EventMessages evtMsgs, ContentSavingEventArgs savingEventArgs)
   at Umbraco.Core.Services.Implement.ContentService.CommitDocumentChangesInternal(IScope scope, IContent content, ContentSavingEventArgs saveEventArgs, Int32 userId, Boolean raiseEvents, Boolean branchOne, Boolean branchRoot)
   at Umbraco.Core.Services.Implement.ContentService.SaveAndPublish(IContent content, String culture, Int32 userId, Boolean raiseEvents)
   at Test.ContentComponent.Initialize() in C:\Users\benpa\Desktop\DELETE ME\Test\Test\ContentComponent.cs:line 27
   at Umbraco.Core.Composing.ComponentCollection.Initialize()
   at Umbraco.Core.Runtime.CoreRuntime.Boot(IRegister register, DisposableTimer timer)

Reproduction

Specifics

Umbraco Version: 8.0.1

Steps to reproduce

  • Set up fresh U8 install
  • Login, create new doc type with alias of “homepage” (allowed at root)
  • Set up component (code posted above)
  • Build, run (after site restart to ensure component code runs)

Expected result

Homepage node created at root of content site.

Actual result

Null reference exception thrown

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11 (8 by maintainers)

github_iconTop GitHub Comments

3reactions
zpqrtbnkcommented, Apr 16, 2019

What happens is this: the RedirectTrackingComponent uses the Current.UmbracoContext.HttpContext to store some state items that need to be carried over the different ContentService event handlers. In a IComponent when running Initialize, since there is no current request, there is no UmbracoContext, and it all ends in a NullReferenceException.

Turns out there is a way to ensure there is a context. Can you try with the following code?

public class ContentComponent : IComponent
{
    private readonly IContentService _contentService;
    private readonly IUmbracoContextFactory _contextFactory;
    
    public ContentComponent(IContentService contentService, IUmbracoContextFactory contextFactory)
    {
        _contentService = contentService;
        _contextFactory = contextFactory;
    }
    
    public void Initialize()
    {
        IContent homepageNode = _contentService.GetRootContent().FirstOrDefault(x => x.ContentType.Alias == "homepage");

        if (homepageNode == null)
        {
            IContent homepage = _contentService.Create("Homepage", -1, "homepage");
            
            using (_contextFactory.EnsureUmbracoContext)
            {
                _contentService.SaveAndPublish(homepage);
            }
        }
    }

    public void Terminate() { }
}

Two things to note:

  • This is one of the few places where we are still using HttpContext to hold some context… and we are slowly getting rid of them as they create an unwanted dependency to System.Web.
  • We are working on making these “context” concepts generally easier to understand and use. It is not always exactly pretty at the moment.
2reactions
martindotcontrolcommented, Sep 17, 2019

I’m facing the same issue, I’m trying to import some data from a API using a BackgroundTaskRunner. The weird part is the save and publish does work at my end it just throws an error.

at LightInject.Web.PerWebRequestScopeManager.GetOrAddScope() at LightInject.Web.PerWebRequestScopeManager.get_CurrentScope() at LightInject.ServiceContainer.GetInstance(Type serviceType) at Umbraco.Core.Composing.LightInject.LightInjectContainer.GetInstance(Type type) at Umbraco.Core.FactoryExtensions.GetInstance[T](IFactory factory) at Umbraco.Web.Runtime.WebInitialComposer.<>c.<Compose>b__0_6(IFactory factory) at Umbraco.Core.Composing.LightInject.LightInjectContainer.<>c__DisplayClass20_01.<Register>b__0(IServiceFactory f) at LightInject.ServiceContainer.GetInstance(Type serviceType) at Umbraco.Core.Composing.LightInject.LightInjectContainer.GetInstance(Type type) at Umbraco.Core.FactoryExtensions.GetInstance[T](IFactory factory) at Umbraco.Deploy.Cloud.LiveEditing.EventSubscriber.GetHubAndHelper(IHubContext& hub, UmbracoHelper& helper) at Umbraco.Deploy.Cloud.LiveEditing.EventSubscriber.ContentService_Published(IContentService sender, PublishEventArgs1 e)`

Read more comments on GitHub >

github_iconTop Results From Across the Web

tomcat - Error in publishing the configuration in Eclipse
Publishing to tomcat v6.0 server at localhost..'has encountered a problem. Publishing the configuration.. tomcat give above error. How to ...
Read more >
Notification – Custom Notifications and Alerts for WordPress
Set unlimited Notifications in your WordPress Admin via the beautiful and ... (saved as a draft) notification; Updated post notification; Post send for ......
Read more >
Errors in error.log on both Author & Publish Instances during ...
Analyzing the error logs, it has been noticed that at the time the errors appeared, the instances were still in Startup mode, not...
Read more >
How to debug SegmentNotFoundException when Issue is ...
How to fix corruption when encountering “ConsistencyChecker - No good revision found” on consistency check · Stop AEM. · Repeat step 3 for...
Read more >
v8.0.0
This is the main Umbraco download, generally you won't need anything else. Downloaded 4888 times - uploaded 26 February 2019. Also available on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found