First, you should NEVER use DynamicProperty class to read a dynamic property because it not using the caching layer!
The correct way to read a property (both user-defined on the page and dynamic properties) is to go through the PageData class:
var value = CurrentPage["MyDynamicPropety"];
string value = CurrentPage["MyDynamicPropety"] as string;
int value = (int)(CurrentPage["MyDynamicPropety"] ?? 0);
To add or change the defenitions you have to work with the class PageDefinition.Try to create a new PageDefenitionclass and set PageTypeID to 0 to indicate that this is a dynamic (=global inheritable) property.
A word of warning: Changing Page Type Definitions in runtime is considered not to be best practice for several reasons. I do hope you have a very good reason of doing this! Consider using another approach if possible, maybe by using DDS.
If you dont want to go through the pagedata class you can use this function
public PropertyData GetPropByPageRef(string propName, PageReference pageRef, string langID)
{
var props = new PropertyDataCollection();
props.Add("PageLanguageBranch", new PropertyString(langID));
props.Add("PageLink", new PropertyPageReference(pageRef));
return DynamicPropertyCache.DynamicPropertyFinder.FindDynamicProperty(propName, props);
}
I can easily read/edit a dynamic property from code:
This works fine if the property already exists - and otherwise crashes with a null reference exception (the Load() method returns null). How can i create the dynamic property if it does not already exist?