Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • J 377 posts 652 karma points
    1 week ago
    J
    0

    Running tasks within IUserComposer Compose method

    Im using this guide to build a section

    https://our.umbraco.com/Documentation/Extending/Section-Trees/sections-v8

    Within this method

    public void Compose(Composition composition)
        {
            composition.Sections().Append<MyFavouriteThingsSection>();
        }
    

    I add some custom code such as creating a file under a directory. I have hardcoded the path for testing i.e. c:\Umbraco\Files\myFile.txt

    public void Compose(Composition composition)
        {
            composition.Sections().Append<MyFavouriteThingsSection>();
            ICustomClass myClass = new MyClass();
            myClass.CreateFile();
        }
    

    When the create file method hits it throws an error (System.Exception: Illegal characters in path) but using the same code outside of this method works successfully.

    Is it possible to take a custom action here or is there another way to achieve this? Ideally i would like to take some actions when a new section is created.

  • Jesper Mayntzhusen 11 posts 107 karma points c-trib
    1 week ago
    Jesper Mayntzhusen
    100

    Composers run on startup, so essentially you want to create your file when the site starts/reboots?

    Don't think you can do it from within the section composer, but essentially you are not really doing anything that needs the section, you could create another component to run your code in:

    Composer:

    public void Compose(Composition composition)
    {
        composition.Sections().Append<MyFavouriteThingsSection>();
        composition.Components().Append<MyFileCreationComponent>();
    }
    

    Component:

    using Umbraco.Core.Composing;
    
    namespace Testing.Composers
    {
        public class MyFileCreationComponent : IComponent
        {
            public void Initialize()
            {
                // Runs when the site starts up
                ICustomClass myClass = new MyClass();
                myClass.CreateFile();
            }
    
            public void Terminate()
            {
                // runs when the site shuts down, maybe some cleanup here?
            }
        }
    }
    

    That being said - I don't really know your usecase, but you probably don't need to create your file when you create the section - rather it should be created whenever some action that needs it is triggered?

Please Sign in or register to post replies

Write your reply to:

Draft