DefconDotNet

TemplateReplacer

Oct 25th, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4.  
  5. namespace SkillSource.Infrastructure.Web
  6. {
  7.     public static class TemplateReplacer
  8.     {
  9.         /// <summary>
  10.         /// Replaces all [tags] and [tag.tags] found in the template with the corresponding value in the model
  11.         /// </summary>
  12.         /// <param name="template">the template</param>
  13.         /// <param name="model">any model</param>
  14.         /// <returns>the filled in template</returns>
  15.         public static string Replace(string template, object model)
  16.         {
  17.             var result = new StringBuilder();
  18.             for (var pos = 0;pos < template.Length;) {
  19.                 var nextOpenBracket = template.IndexOf('[', pos);
  20.                 if (nextOpenBracket >= 0) {
  21.                     result.Append(template.Substring(pos, nextOpenBracket - pos));
  22.                     var nextCloseBracket = template.IndexOf(']', nextOpenBracket);
  23.                     if (nextCloseBracket >= 0) {
  24.                         pos = nextCloseBracket + 1;
  25.                         var path = template.Substring(nextOpenBracket + 1, nextCloseBracket - nextOpenBracket - 1);
  26.                         result.Append(ResolvePath(model, path));
  27.                     }
  28.                     else throw new InvalidOperationException("Bracket at pos " + nextOpenBracket + " not closed!");
  29.                 }
  30.                 else {
  31.                     // till end of template
  32.                     result.Append(template.Substring(pos));
  33.                     break;
  34.                 }
  35.             }
  36.             return result.ToString();
  37.         }
  38.  
  39.         private static string ResolvePath(object model, string paths)
  40.         {
  41.             var parts = paths.Split('.');
  42.             object[] value = {model};
  43.  
  44.             foreach (var property in parts.Select(part => value[0].GetType().GetProperty(part))) {
  45.                 if (property == null) return "[" + paths + "]";
  46.                 value[0] = property.GetValue(value[0], null);
  47.             }
  48.  
  49.             return value[0].ToString();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment