Closed tusmester closed 1 year ago
A sample class that can convert dynamic content types into child classes. It can handle simple fields and defined models so far.
public abstract class BaseSNModel
{
public BaseSNModel(dynamic content)
{
foreach (PropertyInfo prop in GetType().GetProperties())
{
var property = GetType().GetProperty(prop.Name);
PropertyInfo? pi = GetType().GetProperty(prop.Name);
if (property == null || pi == null) continue;
var propType = pi.PropertyType;
if (int.TryParse(content[prop.Name].ToString(), out int number)
&& (propType == typeof(int)))
{
property.SetValue(this, number);
}
else if (bool.TryParse((content[prop.Name] as string)?.ToLower(), out bool boolean)
&& (propType == typeof(bool) || propType == typeof(Boolean)))
{
property.SetValue(this, boolean);
}
else if (propType == typeof(string))
{
property.SetValue(this, content[prop.Name].ToString());
}
else
{
var typeName = String.Concat(GetType().Namespace, ".", prop.Name);
var type = Type.GetType(typeName);
if(type == propType)
{
var refField = Activator.CreateInstance(type, content[prop.Name]);
property.SetValue(this, refField);
}
}
}
}
}
Scenario: get content from sensenet and convert it to a model and pass it on to the client.
This issue is about providing best practices and possibly a reusable code or client API for converting general dynamic content objects into custom models that can be used by the business logic or passed down to the client of an Asp.Net app.