Validating properties in dynamic objects

1.4k Views Asked by At

I am using Scriban to render html templates for a mail service. Scriban allows me to render html, using an object and a html template like the one below:

<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>

I need to validate that certain properties exist in a dynamic object. In the example above, the matching dynamic object needs to contain a "Username" property and a "Password" property.


I have created a solution that works, but it is very hacky, makes me ashamed to call myself a developer, and will in NO WAY be a part of my final solution:

    private readonly string template = "<ul id='model'>\n<h2>Name 2: {{ model.Username }}</h2>\n<h1>Message 2: {{ model.Password }}</h1>\n</ul>";
    private readonly dynamic model = new {Username = "user1", Password = "pass"};
    public void Validate()
    {
        //Convert dynamic object to dictionary
        var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(model));
        //Regex pattern for finding properties in html-string
        Regex pattern = new Regex("(?<={{ )(.*?)(?= }})");
        //Properties in html-string
        MatchCollection matches = pattern.Matches(template);

        //Check if dynamic object contains a property for each match
        foreach (Match match in matches)
        {
            var matchString = match.ToString();
            //Remove "model." from match. This should be done by regex instead.
            var property = matchString.Substring(matchString.IndexOf('.') +1);
            //Throws an exception, if the dynamic object doesnt contain the property.
            var result = data[property];
        }  
    }

How do i validate if a certain property exists in the dynamic object?

1

There are 1 best solutions below

0
On BEST ANSWER

You should try using the Dynamic object class, your model can inherit from the class. This will allow you to control what happens when you try to set/access members of dynamic object.

The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.

See for details: https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.dynamicobject?view=netframework-4.7.2