I've got in my database a varchar column with data on it like this one :
"Hello my name is {person.firstname} and my house is in {city.name}"
I want to inject my objects in this string to get a full data string fill with data from database.
I'm using .Net 4.7 and it's on a API.
Is that easily possible ? Did I need to use Roselyn Code Analysis ?
Thanks !
For given string source
string source =
"Hello my name is {person.firstname} and my house is in {city.name}";
We have to implement 2 steps: first, we should be able for a given name (like person.firstname, city.name) provide a correct response
(say, "John" and "New York"). If you have a some kind of context, a collection of instances to query, e.g.
IEnumerable<object> = new List<object>() {
new Person() {
FirstName = "John",
LastName = "Smith",
Sex = "M",
Age = 44
},
new City() {
Name = "New York",
Country = "USA"
},
...
};
You can put it like this:
private static string MakeResponse(IEnumerable<object> context, string name) {
if (string.IsNullOrEmpty(name))
return "???";
else if (context == null)
return "???";
string[] items = name.Split('.');
string className = items[0];
string propertyName = items.Length > 1 ? items[1] : null;
object data = context
.Where(item => item != null)
.FirstOrDefault(item =>
string.Equals(item.GetType().Name, className, StringComparison.OrdinalIgnoreCase));
if (null == data)
return "???";
if (null == propertyName)
return data.ToString();
var property = data
.GetType()
.GetProperties(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.Static)
.Where(prop => string.Equals(prop.Name, propertyName, StringComparison.OrdinalIgnoreCase))
.Where(prop => prop.CanRead)
.Where(prop => !prop.GetIndexParameters().Any())
.FirstOrDefault();
if (null == property)
return "???";
return property.GetValue(property.GetGetMethod().IsStatic ? null : data)?.ToString() ?? "";
}
Then we have to parse the string, and substitute {...}
private static string ReplaceMyMask(string source, params object[] context) {
if (null == context)
return source;
return Regex.Replace(
source,
@"\{\s*[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*\s*}",
match => MakeResponse(context, match.Value.Trim(' ', '{', '}'))
);
}
Demo:
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class City {
public string Name { get; set; }
}
...
var person = new Person() {
FirstName = "John",
LastName = "Smith",
},
var city = new City() {
Name = "New York"
};
...
string stringToModify =
"Hello my name is {person.firstname} and my house is in {city.name}";
string result = ReplaceMyMask(stringToModify, person, city);
Console.Write(result);
Outcome:
Hello my name is John and my house is in New York
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With