AOP with Roslyn–part 4–custom code to the end of the method

 

A good AOP needs also custom code to the beginning and to the end of the method. So we need to add formatter for the last line.

That means that the MetodRewriter constructor will look like this:

 

public MethodRewriter(string formatterFirstLine,string formatterLastLine=null)
{
   FormatterFirstLine = formatterFirstLine;
   FormatterLastLine = formatterLastLine;
}

 

More, we should put code at the beginning and at the end of the method

if (cmdLastLine!= null)
 blockWithNewStatements = blockWithNewStatements.Insert(0, cmdLastLine);
//code
if(cmdFirstLine != null)
 blockWithNewStatements = blockWithNewStatements.Insert(0, cmdFirstLine);

And the test will make the sentence

var dt=DateTime.Now;

between start and end lines:

[TestMethod]
 public void TestMethodRewriterLastLine()
 {

 var rc = new RewriteCode(
 formatterFirstLine: "Console.WriteLine(\"start {nameClass}_{nameMethod}_{lineStartNumber}\");",
 formatterLastLine: "Console.WriteLine(\"end {nameClass}_{nameMethod}_{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)
 {
 Console.WriteLine(" + "\"start Program_Main_6\"" + @");
 var dt = DateTime.Now;
 Console.WriteLine(" + "\"end Program_Main_6\"" + @");
 }
 }
}";
 Assert.AreEqual(result.Replace(Environment.NewLine, ""), newCode.Replace(Environment.NewLine, ""));
 }


 
 }