Dynamically programmtically extend content type at initialization

Vote:
 

Is it possible (perhaps through an initialization module) to dynamically add additional strongly-typed properties to an existing model/contenttype so that those new properties are fully available in the content editor and persisted in the database, despite not being defined in the actual model class?

#178189
May 04, 2017 11:47
Vote:
 

Interesting, (I may be wrong) Theoratically, an existing class cannot be extended with new members at runtime. However, new class can be created using System.Reflection.Emit that has the existing class as base class. But not sure it will also work at intialization or not. I am wondering, Simple Inheritance usually used to extend some model.
https://msdn.microsoft.com/en-us/library/system.reflection.emit.aspx

/K

#178204
May 04, 2017 15:46
Vote:
 

In an ideal world you sould update your model source code but, in situations where you can't access that model, you could create something as an initialization module as you suggested. Something like this should do it.

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class ModelInitialisation : IInitializableModule
{
    public void Initialize(EPiServer.Framework.Initialization.InitializationEngine context)
    {
        var typeRepo = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
        var contentType = typeRepo.Load("MyContentType");
        var pdr = ServiceLocator.Current.GetInstance<IPropertyDefinitionRepository>();
        if (!contentType.PropertyDefinitions.Any(d => d.Name.Equals("MyNewPropertyName")))
        {
            var dtr = ServiceLocator.Current.GetInstance<IPropertyDefinitionTypeRepository>();
            var tdr = ServiceLocator.Current.GetInstance<ITabDefinitionRepository>();
            var def = new PropertyDefinition();
            def.Name = "MyNewPropertyName";
            def.ContentTypeID = contentType.ID;
            def.EditCaption = "My New Property Name";
            def.Type = dtr.Load(typeof(PropertyString));
            def.Searchable = false;
            def.Required = false;
            def.LanguageSpecific = true;
            def.FieldOrder = 100;
            def.Tab = tdr.Load(SystemTabNames.Settings);
            pdr.Save(def);
        }
    }

}
#178206
May 04, 2017 16:16
Vote:
 

@Paul, this works pretty well -- any idea how to specify a particular editordescriptor or clienteditingclass for this dynamically added property definition?

#178259
May 05, 2017 16:01
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.