Intercept AutoCrud Create/Update to trim all RequestDto's strings?

As I find the AutoGen feature of AutoCrud saves a lot of development time, I was wondering whether it is possible to intercept AutoCrud’s create/update commands, so that all string properties in a RequestDto could be trimmed before being stored in the database?

If it cannot be done generically for all string properties, are there any annotations that can be added to the RequestDto’s string properties? Or could #Script be used? Or could I use the fluent validations mechanism to return a validated and trimmed RequestDTO?

I do not want to implement my own services for each table requiring standard CRUD actions.

You should be able to use OrmLite’s StringFilter to trim all string properties if I’m not mistaken.

Otherwise as it’s just a normal ServiceStack Service you can use all the Request Filters as usual where you’d need to use reflection to inspect all the DTOs string properties, check their values, then replace them if they need trimming.

The Reflection Utils could come in handy, there’s also a PopulateInstance ext method where you could use ToObjectDictionary to turn the POCO into an object dictionary, inspect the dictionary and only retain the string value entries that need updating then use PopulateInstance to populate those modified values back into the instance.

PopulateInstance(this IEnumerable<KeyValuePair<string, object>> values, object instance)

Also I should mention that AutoQuery CRUD does have events you can use OnBefore* and OnAfter* each CRUD operation.

I did not manage to get the OrmLite’s StringFilter to work.

However, after considering my options, I went with a RequestConverter for
update requests, combined with an object dictionary as suggested:

private void ConfigureRequestConverters(Container container)
{
  // trim all incoming string properties
  RequestConverters.Add((req, requestDto) => {
      if ((requestDto is IPost) || (requestDto is IPut))
      {
          var map = requestDto.ToObjectDictionary();
          var map2 = new Dictionary<string, object>();
          foreach (var kvp in map)
          {
              if (kvp.Value is string)
              {
                  var str = ((string)kvp.Value).Trim();
                  map2.Add(kvp.Key, str);
              }
          }

          // string properties trimmed?
          if (map2.Count > 0)
          {
              map2.PopulateInstance(requestDto);
          }
      }
      return Task.FromResult(requestDto);
  });
}

After testing, I think this is a better approach, because it means the trimmed strings are also used in the RequestDto validations.

Please feel free to suggest any improvements to my code or approach.

1 Like

Yep Request Converters also works. I would compare the trimmed string vs the original string so you’re only using reflection to update the properties that needs updating.

Good idea, thank you.