Wiki

Clone wiki

CodeCop / Getting Started

Getting Started

This simple tutorial will show you how quickly you can intercept a method in a class. Please refer to the API Documentation page for more advanced scenarios and usages.

1) Create a new ConsoleApplication and call it HelloWorld (framework 4.0 or upper).

2) Add CodeCop nuget package to your project.

#!powershell

install-package codecop
3) Create a new class, call it WriteMethodNameToConsoleInterceptor, make it implement the ICopIntercept interface and add the following code to the OnBeforeExecute and OnAfterExecute methods.

#!c#
 public class WriteMethodNameToConsoleInterceptor : ICopIntercept
    {

        public void OnBeforeExecute(InterceptionContext context)
        {
            Console.WriteLine("Before {0}", context.InterceptedMethod.Name);
        }

        public void OnAfterExecute(InterceptionContext context)
        {
            Console.WriteLine("After {0}", context.InterceptedMethod.Name);
        }

    }
4) Add a new class file, call it MyClass and add a new void method called InterceptedMethod that makes a call to Console.WriteLine.

#!c#
public class MyClass
    {
        public void InterceptedMethod()
        {
            Console.WriteLine("InterceptedMethod() has executed");
        }
    }

5) Add a new JSON file to your project and call it copconfig.json (mandatory name), right-click on it and in the option Copy to Output Directory select Copy if newer.

6) The JSON file should look like this:

#!json

{
    "Types": [
        {
            "TypeName": "HelloWorld.MyClass, HelloWorld",
            "Methods": [
                {
                    "MethodSignature": "InterceptedMethod()",
                    "Interceptors": [ "WriteMethodNameToConsoleInterceptor"]
                }
            ],
           "GenericArgumentTypes": []

        }

    ],
    "GlobalInterceptors": [],
    "Key":""
}
6) On the application Main method, make a call to the Intercept method of the Cop class to bootstrap the interception process. After, make a call to the InterceptedMethod of MyClass.

#!c#
class Program
    {
        static void Main(string[] args)
        {
            Cop.Intercept();
            new MyClass().InterceptedMethod();
        }
    }

7) Run the app and this is the output you should see.

result.jpg

Pretty Cool, right? :)

Updated