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.
1 2 3 4 5 6 7 8 | public RewriteCode(): this ( "Console.WriteLine(\"{nameClass}_{nameMethod}_{lineStartNumber}\");" ) { } public RewriteCode( string formatter) { Formatter = formatter; } |
The VisitMethod is now much simpler:
1 2 | 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
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | [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, "" )); } } |
2 Responses