AOP with Roslyn–part 3–custom code at beginning of each method

Last time(http://msprogrammer.serviciipeweb.ro/2017/11/27/aop-with-roslynpart-2/)  we have injected a new code into each method . However, this code was pretty much hardcoded into the MethodRewriter class – it was a simple

Console.WriteLine(\”{nameClass}_{nameMethod}_{lineStartNumber}\”);

 

Now we want to can customize this code at the will of the programmer. For this, I have modified classes RewriteCode and MethodRewriter to accept a parameter named Formatter . To run the test that worked previously, I made a parameterless  constructor for RewriteCode in order to preserve compatiblity.

 

 

public RewriteCode(): this("Console.WriteLine(\"{nameClass}_{nameMethod}_{lineStartNumber}\");")
{

}
public RewriteCode(string formatter)
{
    Formatter = formatter;
}

 
The VisitMethod is now much simpler:

string nameVariable =Formatter.FormatWith(new { nameClass,nameMethod,lineStartNumber=lineStart.Line});
var cmd = SyntaxFactory.ParseStatement(nameVariable);

 
( The .FormatWith is an extension from https://github.com/crozone/FormatWith )
 
Also, I have made a new test to test this one – and I have inserted into code an variable named s:
 
string s=\”this is method {nameMethod} from class {nameClass} at line {lineStartNumber}\”;”
 
 
The test is

[TestMethod]
public void TestMethodRewriterAddVariable()
{

var rc = new RewriteCode(
"string s=\"this is method {nameMethod} from class {nameClass} at line {lineStartNumber}\";"
);
rc.Code = @"
using System;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
              var dt=DateTime.Now;
        }
     }
}";
            var result = rc.RewriteCodeMethod();
            var newCode = @"
using System;

namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = ""this is method Main from class Program at line 6"";
            var dt = DateTime.Now;
        }
    }
}";
            Assert.AreEqual(result.Replace(Environment.NewLine, ""), newCode.Replace(Environment.NewLine, ""));
        }
    }