Anup
Anup

Reputation: 9738

Extracting Placeholders from a String & Store them in an Array

I need to replace Placeholders for Email in C#. The pattern for Placeholders is like this :-

| following Table Name is used to identify from which database table to bring data from.

Hi [NAME|MAIN],
Your Address is : [ADDRESS|MAIN]

Your Code & PAN :-
[CODE|SUB]
[PAN|SUB]

Above code is stored in a string. I want to store Placeholders of MAIN category in an Array & SUB category in a different Array, so that i can replace them with actual values.

How to extract this Placeholders & store them in Array or List?

Upvotes: 1

Views: 1090

Answers (2)

Priyang
Priyang

Reputation: 386

I agree with comments of kape123, you will need to rethink about solution design.

What I will suggest you can use T4 Template functionality that is available with C# and it will help you with html page generation that you can export as string.

You can create a template like this

<html><body>
 The date and time now is: <#= DateTime.Now #>
</body></html>

and same way you can design your email in template file and feed in your class to it. It will automatically generate email text in desired format based on value available in class.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<# var properties = new string [] {"P1", "P2", "P3"}; #>
// This is generated code:
class MyGeneratedClass {
<# // This code runs in the text template:
 foreach (string propertyName in properties) 
  { #>
   // Generated code:
   private int <#= propertyName #> = 0;
  <# } #>
 }

above template will generate a new class like following

class MyGeneratedClass {
 private int P1 = 0; 
 private int P2 = 0;
 private int P3 = 0;

}

Please refer this.

More information is available here.

Upvotes: 0

nikib3ro
nikib3ro

Reputation: 20606

Obviously you can do this with Regex:

var str =
@"Hi [NAME|MAIN],
Your Address is : [ADDRESS|MAIN]

Your Code & PAN :-
[CODE|SUB]
[PAN|SUB]
";
var matches = Regex.Matches(str, @"\[\w*\|\w*\]");
foreach (var m in matches)
{
    Console.WriteLine(m);
}

However, I would STRONGLY recommend that you reconsider this approach. Instead of allowing your email templates to dictate which database fields will be referenced get appropriate objects from database and use something like SmartFormat.NET.

With this approach I can already see two big problems off the top of my head that are highly likely to happen:

  1. Maintenance problem down the line - if any table or column is renamed, do you think developer will remember that he should check email templates and change the ones that reference the field?

  2. Possible security problem - obviously you can contain this... but the fact that you pull up data directly from database doesn't prevent cases like [PASSWORD|MAIN].

Upvotes: 2

Related Questions