Context:
I need to fill a handful of .docx templates with answers that come from form.responses, which is a dynamic object that comes from a JSON and can have different properties that vary according to the type of the form that was answered.
To do the filling, we need to instantiate a DTO called BindDto that takes the template string (eg.: ${PersonName}) and the value that will replace it (eg.: form.responses.client_name = "John Doe").
In my case, I created some [X]Constants classes that have properties that look like this...
public static readonly KeyValuePair<string, string> PERSON_NAME = new KeyValuePair<string, string>("client_name", "${PersonName}");
public static readonly KeyValuePair<string, string> PERSON_AGE = new KeyValuePair<string, string>("my_age", "${PersonAge}");
public static readonly KeyValuePair<string, string> MOTHER_NAME = new KeyValuePair<string, string>("mother", "${MotherName}");
...to map which template string each field from the JSON correponds to.
The code below was written so I could fill all the templates independent from which fields they might have by searching the [X]Constants classes and using the KeyValuePairs that I have set.
It works (o' course), but it seems I little... clumsy. And I don't have enough knowledge about C# to be sure this isn't pure madness.
What do you think about this code? Is it valid? Is is overengineering? How can I improve it?
I don't think performance will ever be a concern, but I would like to be enlightened in that sense too.
Thanks in advance to anyone willing to discuss it!
public List<BindDto> GenerateBinds(IEnumerable<Form> forms)
{
var constants = new List<FieldInfo>();
var binds = new List<BindDto>();
constants.AddRange(typeof(AuthConsts).GetFields());
constants.AddRange(typeof(ClientConsts).GetFields());
constants.AddRange(typeof(ContactConsts).GetFields());
constants.AddRange(typeof(AddressConsts).GetFields());
constants.AddRange(typeof(ReferenceConsts).GetFields());
foreach (var form in forms)
{
var formResponses = form.response.ToObject<Dictionary<string, string>>();
IEnumerable<string> formFields = formResponses.Keys;
foreach (var field in formFields)
{
foreach (var constant in constants)
{
if (constant.FieldType == typeof(KeyValuePair<string, string>))
{
var templateString = (KeyValuePair<string, string>)constant.GetValue(this);
if (templateString.Key == field)
binds.Add(new BindDto(templateString.Value, formResponses[field]));
}
}
}
}
return binds;
}