Reputation: 4633
I have functions that sends out email messages using specific string formats for different messages.
Below is a sample:
String BodyText = "Information \r\n \r\n ID: " + id + " \r\n \r\n Title: " + title + " \r\n \r\n Description: " + description"
As the messages contain variables, is it possible for my message to be configurable in the config file?
Thank you.
Upvotes: 0
Views: 241
Reputation: 920
Use String.Format
and put your string into the config file like this:
<appSettings>
<add key="BodyText" value="Information \r\n \r\n ID: {0}\r\n \r\n Title: {1}\r\n \r\n Description: {2}"/>
</appSettings>
Then you can use the value in code like this:
var bodyText = ConfigurationManager.AppSettings["BodyText"];
String.Format(bodyText, id, title, description);
Note, you will need to add a project reference to System.Configuration
and then add the corresponding using
statement to the file.
Upvotes: 1
Reputation: 2177
You have a few options here:
You could parse variables in a string from config, giving something looking like this:
My email here is sent to {{firstname}} etc.
To implement this, you could do a regex search to inject variable values into your symbols ie {{firstname}}
or alternately you could look at implementing something like the visitor gang of four pattern which will make a more unit testable setup where each variable is additive to code, as opposed to part of a hard-coded blob that needs modifying each time a variable is introduced.
You could use Roslyn to pull the code in from config and just compile it on the fly. I would highly not recommend this due to the security and zillion error scenarios that could occur.
Upvotes: 1