Giter VIP home page Giter VIP logo

methoddecorator's Introduction

MethodDecorator.Fody

Chat on Gitter NuGet Status

Compile time decorator pattern via IL rewriting.

See Milestones for release notes.

This is an add-in for Fody

It is expected that all developers using Fody become a Patron on OpenCollective. See Licensing/Patron FAQ for more information.

Usage

See also Fody usage.

NuGet installation

Install the MethodDecorator.Fody NuGet package and update the Fody NuGet package:

PM> Install-Package Fody
PM> Install-Package MethodDecorator.Fody

The Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.

Your Code

// Attribute should be "registered" by adding as module or assembly custom attribute
[module: Interceptor]

// Any attribute which provides OnEntry/OnExit/OnException with proper args
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
public class InterceptorAttribute : Attribute, IMethodDecorator	{
    // instance, method and args can be captured here and stored in attribute instance fields
    // for future usage in OnEntry/OnExit/OnException
    public void Init(object instance, MethodBase method, object[] args) {
        TestMessages.Record(string.Format("Init: {0} [{1}]", method.DeclaringType.FullName + "." + method.Name, args.Length));
    }

    public void OnEntry() {
        TestMessages.Record("OnEntry");
    }

    public void OnExit() {
        TestMessages.Record("OnExit");
    }

    public void OnException(Exception exception) {
        TestMessages.Record(string.Format("OnException: {0}: {1}", exception.GetType(), exception.Message));
    }
}

public class Sample	{
    [Interceptor]
    public void Method()
    {
        Debug.WriteLine("Your Code");
    }
}

What gets compiled

public class Sample {
    public void Method(int value) {
        InterceptorAttribute attribute =
            (InterceptorAttribute) Activator.CreateInstance(typeof(InterceptorAttribute));

        // in c# __methodref and __typeref don't exist, but you can create such IL
        MethodBase method = MethodBase.GetMethodFromHandle(__methodref (Sample.Method), __typeref (Sample));

        object[] args = new object[1] { (object) value };

        attribute.Init((object)this, method, args);

        attribute.OnEntry();
        try {
            Debug.WriteLine("Your Code");
            attribute.OnExit();
        }
        catch (Exception exception) {
            attribute.OnException(exception);
            throw;
        }
    }
}

NOTE: this is replaced by null when the decorated method is static or a constructor.

IntersectMethodsMarkedByAttribute

This is supposed to be used as

// all MSTest methods will be intersected by the code from IntersectMethodsMarkedBy
[module:IntersectMethodsMarkedBy(typeof(TestMethod))]

You can pass as many marker attributes to IntersectMethodsMarkedBy as you want

[module:IntersectMethodsMarkedBy(typeof(TestMethod), typeof(Fact), typeof(Obsolete))]

Example of IntersectMethodsMarkedByAttribute implementation

[AttributeUsage(AttributeTargets.Module | AttributeTargets.Assembly)]
public class IntersectMethodsMarkedByAttribute : Attribute {
    // Required
    public IntersectMethodsMarkedByAttribute() {}

    public IntersectMethodsMarkedByAttribute(params Type[] types) {
        if (types.All(x => typeof(Attribute).IsAssignableFrom(x))) {
            throw new Exception("Meaningfull configuration exception");
        }
    }
    public void Init(object instance, MethodBase method, object[] args) {}
    public void OnEntry() {}
    public void OnExit() {}
    public void OnException(Exception exception) {}
    // Optional
    //public void OnTaskContinuation(Task task) {}
}

Now all your code marked by [TestMethodAttribute] will be intersected by IntersectMethodsMarkedByAttribute methods. You can have multiple IntersectMethodsMarkedByAttributes applied if you want (don't have idea why). MethodDecorator searches IntersectMethodsMarkedByAttribute by predicate StartsWith("IntersectMethodsMarkedByAttribute")

In case of exception in async method you "OnException" will not be called, OnTaskContinuation will be called instead.

Icon

Icon courtesy of The Noun Project

methoddecorator's People

Contributors

304notmodified avatar aiexandr avatar alansingfield avatar alex-y-su avatar andyhoyle avatar citizenmatt avatar davidalpert avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dterziev avatar erikeckhardt avatar icnocop avatar ltrzesniewski avatar megafinz avatar simoncropp avatar sstronin avatar tom-englert avatar ursenzler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

methoddecorator's Issues

Need OnSuccess action

Currently the code in the target method gets wrapped in a try-catch and OnExit is placed at the end of try block. PostSharp handles OnExit the same, but creates a try-catch-finally and puts OnSuccess call into the finally block. Would be a nice addition for completeness.

The advantage here is that I can have exception handling in my original method, and use the attribute to place a common clean-up/logging code in the finally block (regardless of whether there was an exception or not it will execute). Right now I have to re-throw exception after handling it (with additional state indicating that it was handled), so Fody's OnException will catch it. I don't like this, it make the logic messy, so I avoid using Fody in these situations and just copy-paste boilerplate code = BAD™.

Invalid Program when release build

I am using MethodDecorator to do some logging on some of my methods. It worked great until I made a Release build. Then I got exceptions for 'Common Language Runtime detected an invalid program.'

I removed the method decorator attribute usages from the methods and the exceptions went away.

The problem seems similar to Fody/MethodTimer#2. I also see errors if I use JustDecompile to view the assembly. The classes that use my IMethodDecorator are not viewable. The other classes are viewable.

But it is not similar in that my methods are not marked as async. I am using the async targeting pack, but the specific methods that were causing the errors are 'public virtual void'. And another strange thing is that other methods using the IMethodDecorator are not causing problems.

A workaround is to apply the [Conditional("DEBUG")] attribute to tje IMethodDecorator attribute and then the release build works fine -- without the method decorator functionality.

.NET Core support

Is it possible to use it with .NET Core support? Tried all packages, event MethodDecorator.Fody.PP.
Even tried to pull current version locally, changed everything to netstandard2.0, added dependency to Fody.Cecil >2.00, it compiles, but when referencing my project to the new one .NET Standard 2.0 Library, it thorws error of

Severity	Code	Description	Project	File	Line	Suppression State
Error		Fody: An unhandled exception occurred:
Exception:
Could not load file or assembly 'MethodDecorator.Fody.dll' or one of its dependencies. The system cannot find the path specified.
Type:
System.IO.FileNotFoundException
StackTrace:
   at System.Reflection.AssemblyName.nGetFileInformation(String s)
   at System.Reflection.AssemblyName.GetAssemblyName(String assemblyFile)
   at AssemblyVersionReader.GetAssemblyVersion(String path)
   at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
   at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
   at System.Linq.OrderedEnumerable`1.<GetEnumerator>d__1.MoveNext()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at AddinFinder.FindAddinAssembly(String packageName)
   at Processor.FindAssemblyPath(String weaverName)
   at Processor.ProcessConfig(WeaverEntry weaverConfig)
   at Processor.ConfigureWhenWeaversFound()
   at Processor.FindWeavers()
   at Processor.Inner()
   at Processor.Execute()
Source:
mscorlib
TargetSite:
System.Reflection.AssemblyName nGetFileInformation(System.String)
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
Type:
System.IO.DirectoryNotFoundException
	Thrust.SCooB.Commons		1	

All otther packages gave me the error, that the package is out of dated and that i needed to reference Mono.Cecil 0.10 at least inside the package for Mono.Cecil v2 or higher.

How to proceed to weaver an .NET Core project?

Update to Fody Version 2

Fody Version 2 is out and you will need to do an update for your addin to be usable with it

Specifically:

  • Update to the newest Fody.Cecil nuget
  • Change the min dependency range for Fody to be at least 2.0

Please ping me if u need help

Can't debug anymore after decorating.

After decorating with MethodDecorator any method of a library,when i set a breakpoint and i try to debug I get an error in visual studio 2013 "Source Information Not Avaible" "Source information is missing from the debug information" and i'm unable to debug my code.
What could be the problem?
Thanks in advance.

Asynchronous methods calling OnExit too Early

I was doing a simple test that uses both MethodTimer fody package and the MethodDecorator to hopefully achieve something I require. However, when simply testing the project out with Console.Write("OnExit"); in the OnExit method, it seems to be printed far sooner than one expects for an asynchronous method. I know that the asynchronous method itself has not yet finished because the MethodTimer is measuring the execution time and that doesn't output to the console until a few seconds later.
Am I missing something as to what kinds of async are allowed? Or can anyone point me in the right direction of getting asynchronous methods to work?

Extra parameters on OnException

Why is there a parameter count check in ModuleWeaver? I would like to add extra parameters to the OnException method but I can't. If this isn't acceptable, maybe you could add the extra parameters in the code itself?

Is there anyway to have these parameters on the OnException method?
[CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0

Or at least the latter two (since member name is already obtained)?

Attach interceptor on all method in assembly/namespace.

Hi,

Would the ability to add feature to define interceptors at the assembly?
I would like to be able to automatically attach interceptors to all method in the library. (or only on defined namespace)
PostSharp contains a similar function. For Example:
[assembly: ExceptionAspect (AttributeTargetTypes ="OurApplication.Controllers. *")]
I think that this feature would increase the usefulness of this framework.

NuGet package for MethodDecoratorEx not installing

I have been trying to install the MethodDecoratorEx through Nuget to no avail. I'm am not sure if this is expected but when I install the package, The FodyWeavers.xml and packages.config are added as I had neither prior to installing. However, neither the dependency Fody or the MethodDecoratorEx itself show up in my references. Is this expected or am I simply doing something wrong? I should note that I have used MethodTimer in the past and the dependency Fody doesn't appear when I install that package either but MethodTimer itself shows up in my references.
Thanks

MethodDecorator use in Universal app

Hi,

I used PropertyChanged and MethodDecorator in 2016-2017 in a Universal Windows app (UAP) and it worked like a charm. Now I'm developing that app again and can't build it because Fody throws an error:

Error Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.0.4, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll (cecilReference.Version). At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 1.0.

And can't install FodyCecil, because FodyCecil 2.3.21 is not compatible with UAP,Version=v10.0.

How can I solve this issue? Will it be built to UAP too?

Thanks in advance,
Daniel

Teamcity Build failing with multiple mscorlib versions

Hi,

We've started using Fody MethodDecorator...
In VS2015 it builds and runs OK, but when we try to build the project in Teamcity we get the following error.....
Does anyone have any suggestions as to the cause and what we can do to solve this?
Build server is running TC version 10.

Thanks
Yossi

[Fody.WeavingTask]   Fody: Weaver E:\Build\Code\.........\MethodDecorator.Fody.0.9.0.6\MethodDecorator.Fody.dll'.
[Fody.WeavingTask]   Fody:   Initializing weaver
[Fody.WeavingTask]   Fody:   Loading 'E:\Build\Code\......\Packages\MethodDecorator.Fody.0.9.0.6\MethodDecorator.Fody.dll' from disk.
[Fody.WeavingTask]     Fody/MethodDecorator:   Executing Weaver 

[Fody.WeavingTask] Fody: An unhandled exception occurred:
Exception:
Error occured during IL weaving. The new assembly is now referencing more than one version of mscorlib: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
StackTrace:
  at ModuleWeaver.Execute()
  at lambda_method(Closure , Object )
  at InnerWeaver.ExecuteWeavers() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 161
  at InnerWeaver.Execute() in C:\projects\fody\FodyIsolated\InnerWeaver.cs:line 82
Source:
MethodDecorator.Fody
TargetSite:
Void Execute()

Which nupkg should we be using?

I'm seeing two different nuget packages MethodDecorator.Fody and MethodDecoratorEx.Fody. I see from another issue there was chatter about merging the two, but I also see that the Ex version is more recent on Nuget. I'm just wondering which version is the current one, and, should the other one be deprecated?

Allow method decorating on entire assembly with an assembly attribute.

It would be nice if we could use an assembly attribute and have the method decorator work on all types in the assembly rather than having to put the attribute on each method.

I tried to copy the type finding logic from MethodTimer but I kept getting exceptions. I'll take another stab at it when I have some more time but if someone else knows an easy way to do this, seems like it would be useful.

Playing nice with async exceptions

It would be great if method decorators would play nice with async exceptions. What would be involved in making this happen?

Looking at the AsyncErrorHandler repo, it walks the instruction stack and looks for the SetException methods and injects prior to that. Would that approach be valid here? Or is there something obvious I am overlooking?

Logger as a parameter

I want to use it to log exceptions of method and I am wondering how do I pass a logger instance to the interception class. Is there any way to do it?

IMethodDecorator methods being called twice.

I just decompiled one of my methods that has been decorated with my AnalyticsAttribute

original

[Analytics("Command to get either current or planned outages.")]
public override async void Execute(object parameter)
{
    var vm = (OutagePageViewModel)parameter;
    using (new Busy(vm))
    {
        await RunSafe(GetOutagesTask(vm));
    }
}

decompiled

 [Analytics("Command to get either current or planned outages.")]
    public override void Execute(object parameter)
    {
      // ISSUE: method reference
      // ISSUE: type reference
      MethodBase methodFromHandle1 = MethodBase.GetMethodFromHandle(__methodref (GetOutagesCommand.Execute), __typeref (GetOutagesCommand));
      AnalyticsAttribute analyticsAttribute1 = (AnalyticsAttribute) Activator.CreateInstance(typeof (AnalyticsAttribute));
      object[] args1 = new object[1]
      {
        parameter
      };
      analyticsAttribute1.Init((object) this, methodFromHandle1, args1);
      analyticsAttribute1.OnEntry();
      try
      {
        // ISSUE: method reference
        // ISSUE: type reference
        MethodBase methodFromHandle2 = MethodBase.GetMethodFromHandle(__methodref (GetOutagesCommand.Execute), __typeref (GetOutagesCommand));
        AnalyticsAttribute analyticsAttribute2 = (AnalyticsAttribute) Activator.CreateInstance(typeof (AnalyticsAttribute));
        object[] args2 = new object[1]
        {
          parameter
        };
        analyticsAttribute2.Init((object) this, methodFromHandle2, args2);
        analyticsAttribute2.OnEntry();
        try
        {
          // ISSUE: variable of a compiler-generated type
          GetOutagesCommand.\u003CExecute\u003Ed__0 stateMachine;
          // ISSUE: reference to a compiler-generated field
          stateMachine.\u003C\u003E4__this = this;
          // ISSUE: reference to a compiler-generated field
          stateMachine.parameter = parameter;
          // ISSUE: reference to a compiler-generated field
          stateMachine.\u003C\u003Et__builder = AsyncVoidMethodBuilder.Create();
          // ISSUE: reference to a compiler-generated field
          stateMachine.\u003C\u003E1__state = -1;
          // ISSUE: reference to a compiler-generated field
          stateMachine.\u003C\u003Et__builder.Start<GetOutagesCommand.\u003CExecute\u003Ed__0>(ref stateMachine);
          analyticsAttribute2.OnExit();
        }
        catch (Exception ex)
        {
          analyticsAttribute2.OnException(ex);
          throw;
        }
        analyticsAttribute1.OnExit();
      }
      catch (Exception ex)
      {
        analyticsAttribute1.OnException(ex);
        throw;
      }
    }

What I'm seeing is a lot more bloat that I'd expect.

Why is there a analyticsAttribute1 and an analyticsAttribute2 being generated? What seems to be happening is that all of my methods are getting logged twice.

When using MethodDecorator on .Net 2.0 or Portable assembly it adds an extra reference to mscorlib 4.0.0.0

I tried using Fody.MethodDecorator on a .Net 3.5 assembly and got an extra reference to mscorlib and as a result the assembly referred to both mscorlib 2.0.0.0 and mscorlib 4.0.0.0. This is expected behaviour when the TypeReference objects needed for the IL rewrite are obtained via typeof() and then methodDefinition.Import(type). Because Fody and MethodDecorator are .Net 4 assemblies, the types are defined in mscorlib 4.0.0.0 and Cecil has no choise but to add a reference to the 4.0.0.0 version.

This is also a problem with portable libraries. In this case using method decorator will add a direct reference to mscorlib 4.0.0.0 and therefore potentially breaking the portability of the class library.

To resolve this issue the TypeReference instances needed for the IL rewrite have to be obtained from the mscorlib referenced by the target assembly.

Update Nuget build

The Nuget package is a few versions behind now, can this be updated please?

Return custom value

Is there a way to force the method return some value based on argument checks?

I can't seem to catch exceptions thrown from an async method

Hi There,

This looks like a great project and I was hoping to use it for managing exceptions in a mobile application. However, most of the methods need to be async and it when I decorate my async method (returning a task) it doesn't get caught by my attribute.

Have you seen this before, is it a supported scenario?

it's likely that I am just doing something wrong, so this is more of a question than an issue.

Thanks for any help you can give me.

Rob

Paket Compatibility

Currently there are install.ps1 and uninstall.ps1 scripts which Paket (as long as any other CLI tool) doesn't support. My main complaint is that Fody_ToBeDeleted.txt file is added to every project that uses the package, so I have to manually delete those files each time I install or update packages since that doesn't happen automatically due to the fact that install.ps1 is not executed.

Does this project need a new maintainer

@citizenmatt @alexeysuvorov

So i have pushed a few minor things to this repo over the years. but i dont really consider myself an owner. I dont actively use the project and do not actively monitor the issues.

From looking at the history am i safe in assuming neither of you are interested in actively maintaining this moving forward?

Do we need to put a call out for other maintainers?

How to get return Value?

This is the closest I've seen that allows me to decorate methods and insert boiler plate code. However, specifically for logging, I would like to capture the returned object from the wrapped method and log that as well.

It does not appear that this has been implemented, and I'm a bit lost on where to add it if I fork.

Guidance would be appreciated.

Flag to prevent rethrow

What is the appetite to adding a flag that prevents the re-throw of the exception in OnException? I'd like to be able to keep my application alive in the case of an error.

If I wrap potentially volatile code in a try/catch, then decorate the outer method with my Interceptor, the OnError never triggers because the try/catch caught it. I'd like to have a logger log the error, but keep the app up.

Essentially the bit in the readme that says

    catch (Exception exception) {
        attribute.OnException(exception);
        throw;
    }

would have something like

    catch (Exception exception) {
        attribute.OnException(exception);
        if(!ContinueOnException)
            throw;
    }

Compatibility with new Fody

I did break a few things but my fork works with newest Fody and net 4.7
Fixes issue #521 when build fails with
Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.1.6, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll. Expected strong name token of '1C-A0-91-87-7D-12-CA-03' but got '50-CE-BF-1C-CE-B9-D0-5E'. The weaver needs to update to at least version 3.0 of FodyHelpers.
or
Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.0.4, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll 0.9.6.0. At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 3.0.

Here's the fork: https://github.com/Delfistyaosani/MethodDecorator

IMethodDecorator can't be in a namespace

I don't know if this is an intentional constraint or not, but I found it very confusing that the IMethodDecorator type was not detected since you are checking FullName instead of Name. The error message didn't help either:

"Could not find type 'IMethodDecorator' or 'MethodDecoratorAttribute'"

I had to dig through source to find out what the issue was.

I could submit a patch to check Type::Name instead of Type::FullName, but I don't know enough about the implications here, so this issue is really more of a question.

Thanks,

Matt

Should OnExit be contained within a finally block?

Should

public class Sample {
    public void Method(int value) {
        InterceptorAttribute attribute = 
            (InterceptorAttribute) Activator.CreateInstance(typeof(InterceptorAttribute));

        // in c# __methodref and __typeref don't exist, but you can create such IL 
        MethodBase method = MethodBase.GetMethodFromHandle(__methodref (Sample.Method), 
                                                           __typeref (Sample));

        object[] args = new object[1] { (object) value };

        attribute.Init((object)this, method, args);

        attribute.OnEntry();
        try {
            Debug.WriteLine("Your Code");
            attribute.OnExit();
        }
        catch (Exception exception) {
            attribute.OnException(exception);
            throw;
        }
    }
}

be

public class Sample {
    public void Method(int value) {
        InterceptorAttribute attribute = 
            (InterceptorAttribute) Activator.CreateInstance(typeof(InterceptorAttribute));

        // in c# __methodref and __typeref don't exist, but you can create such IL 
        MethodBase method = MethodBase.GetMethodFromHandle(__methodref (Sample.Method), 
                                                           __typeref (Sample));

        object[] args = new object[1] { (object) value };

        attribute.Init((object)this, method, args);

        attribute.OnEntry();
        try {
            Debug.WriteLine("Your Code");
        }
        catch (Exception exception) {
            attribute.OnException(exception);
            throw;
        }
        finally {
            attribute.OnExit();
        }
    }
}

Init method not invoked

I have implemented everything best to my knowledge IMethodDecorator outside of a namespace. The version is 0.8.1.1.

public interface IMethodDecorator
{
    void Init(object instance, MethodBase method, object[] args);
    void OnEntry(MethodBase method);
    void OnExit(MethodBase method);
    void OnException(MethodBase method, Exception exception);
}

The interceptor

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Module)]
public class InterceptorAttribute : Attribute, IMethodDecorator
{

    public void Init(object instance, MethodBase method, object[] args)
    {

    }

    public void OnEntry(MethodBase method)
    {
        //called on enter
    }
    public void OnExit(MethodBase method)
    {
        //called on exit
    }
    public void OnException(MethodBase method, Exception exception)
    {
        // called if exception happens
    }
}

and added [module:Interceptor] to the AssemblyInfo.cs

The result is, that The OnEntry, and OnExit methods get executed, But the Init method never does.

Any suggestions how.

Unhandled exception occurred - Xamarin Forms

Hi all,

I am trying out Fody for a Xamarin Forms app. However, I keep getting "Unhandled Exception Occurred". Now I tried the same code (note the versions of MD.Fody since I could not get the latest version to work) in a console app and everything worked like a charm. Any pointers as to what I am doing wrong? I have attached the sample code.

App1.zip

Please fix this error

MSBUILD : error : Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.0.4, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll (cecilReference.Version). At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 2.0.

Out of date version of Mono.Cecil.dll

When trying to compile my assembly:

Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.0.4, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll (cecilReference.Version). At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 2.0.

Could not load assembly "MethodDecoratorInterfaces"

I've installed Fody and MethodDecoratorEx into my PCL (only), and I've created an IMethodDecorated (without a namespace) inside the same PCL. I have not installed either of the two packages in any other project.

using System;
using System.Reflection;

// ReSharper disable once CheckNamespace
// intentionally not in a namespace.
public interface IMethodDecorator
{
    void Init(object instance, MethodBase method, object[] args);
    void OnEntry();
    void OnExit();
    void OnException(Exception exception);
}

I've created an interceptor implementing it.

using System;
using System.Diagnostics;
using System.Reflection;
using MyApp.Core.Logging;

[module: LoggingInterceptor]

namespace MyApp.Core.Logging
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
    public class LoggingInterceptor : Attribute, IMethodDecorator
    {
        public LoggingInterceptor() { }

        public void Init(object instance, MethodBase method, object[] args)
        {
            Debug.WriteLine("Entering Method");
        }

        public void OnEntry()
        {
            Debug.WriteLine("Starting Method");
        }

        public void OnExit()
        {
            Debug.WriteLine("Exiting Method");
        }

        public void OnException(Exception exception)
        {
            Debug.WriteLine("Exception was thrown");
        }
    }
}

and I've decorated a class inside my PCL with the interceptor.

The issue I've run into is that when I try and deploy my android app (that uses the pcl), I get the following error.

Error 7 Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'MethodDecoratorInterfaces, Version=0.9.0.4, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'MethodDecoratorInterfaces.dll'
at Xamarin.Android.Tuner.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(ICollection`1 assemblies, AssemblyDefinition assembly, Boolean topLevel)
at Xamarin.Android.Tasks.ResolveAssemblies.Execute() MyApp.Droid

Is this a bug in MethodDecorator, or am I missing something in my code? Am I supposed to also install Fody in my Droid project? If so, I get another error that I don't have any registered weavers. I _CAN_ build the PCL on it's own, it's only when I try and deploy the droid app that the error shows up.

note: it appears as though I'm not the only one

Running tests

I've forked the project (but not made any changes yet) and am trying to run the tests. I get the following error when trying to run any test:

Test Name:	MethodDecoratorEx.Fody.Tests.DecoratingConstructors.ShouldReportOnEntryAndException
Test FullName:	MethodDecoratorEx.Fody.Tests.DecoratingConstructors.ShouldReportOnEntryAndException
Test Source:	F:\Git\MethodDecorator\MethodDecorator.Fody.Tests\DecoratingConstructors.cs : line 19
Test Outcome:	Failed
Test Duration:	0:00:00.001

Result StackTrace:	
at MethodDecoratorEx.Fody.Tests.SimpleTestBase..ctor()
   at MethodDecoratorEx.Fody.Tests.DecoratingConstructors..ctor()
----- Inner Stack Trace -----
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at Mono.Cecil.ModuleDefinition.Write(String fileName, WriterParameters parameters) in C:\Code\cecil\Mono.Cecil\ModuleDefinition.cs:line 1122
   at WeaverHelper.Weave() in F:\Git\MethodDecorator\MethodDecorator.Fody.Tests\Helpers\WeaverHelper.cs:line 54
   at MethodDecoratorEx.Fody.Tests.SimpleTestBase.CreateAssembly() in F:\Git\MethodDecorator\MethodDecorator.Fody.Tests\SimpleTestBase.cs:line 24
   at MethodDecoratorEx.Fody.Tests.SimpleTestBase..cctor() in F:\Git\MethodDecorator\MethodDecorator.Fody.Tests\SimpleTestBase.cs:line 8
Result Message:	
System.TypeInitializationException : The type initializer for 'MethodDecoratorEx.Fody.Tests.SimpleTestBase' threw an exception.
---- System.IO.IOException : The process cannot access the file 'F:\Git\MethodDecorator\TestAssemblies\SimpleTest\bin\Debug\SimpleTest2.dll' because it is being used by another process.

It looks like I'm not the only one with problems running the tests given the comments in the open pull request. Is there something I am missing in regards to getting them to run or do they just not work any more?

(if it helps I'm using VS2015 update 3 on Windows Server 2012 R2)

CA1062 Errors

I originally submitted this issue to the Fody project: Fody/Fody#163. However, it seems to be an issue with this plug in.

Including MethodDecorator in a project causes code analysis to raise false positive errors. Specifically CA1062: Validate arguments of public methods.

See the following repo that demonstrates the error: https://github.com/dalealleshouse/FodyExample.

Thank you very much for your time!

Configurable Parameter to Active/Passive

Hi All,

I write my method decorator and add to my code as attribute. But I want to activate or make passive according to deployment environment by build action. Is there any kind of action/configurable parameter?

Thanks,

MethodDecorator cannot be used across assemblies

Hi.

I'm trying to use the MethodDecorator Fody, but to place my attribute (and its IMethodDecorator interface) in some common project. This will allow me to use the attribute across my solution, in more than one project, rather than redefine it in each project.

The addin doesn't seem to support this, I get: Could not find type 'IMethodDecorator' or 'MethodDecoratorAttribute'. Rummaging through MethodDecorator's ModuleWeaver.cs, it seems that it indeed only looks for types named IMethodDecorator or MethodDecoratorAttribute in the same assembly.

I'd be glad to help out and submit a pull request. However, extending this to support external assemblies seems like it would be heavy - walking through the entire assembly dependency to see if any attributes implement an interface with the name IMethodDecorator. It seems like a case where simply forcing the user to extend a Fody-provided IMethodDecorator could be saner?

Let me know what you think...

Shay

"PM> Install-Package MethodDecorator.Fody" doesn´t work but "PM> Install-Package MethodDecoratorEx.Fody" does.

The nuget package MethodDecorator.Fody doesn´t work on compile, keeps complaining about the IMethodDecorator interface not being correct even after trying the folllowing:

public interface IMethodDecorator
{
    void Init(object instance, MethodBase method, object[] args);
    void OnEntry();
    void OnExit();
    void OnException(Exception exception);
}

and the older syntax

public interface IMethodDecorator
{
    void Init(object instance, MethodBase method, object[] args);
    void OnEntry(MethodBase method);
    void OnExit(MethodBase method);
    void OnException(MethodBase method, Exception exception);
}

I´ve tried defining the classes on root namespace and module register the attribute.

But got it working when i used the MethodDecoratorEx.Fody package instead:

[assembly: MethodDecorator]

public interface IMethodDecorator
{
    void Init(object instance, MethodBase method, object[] args);
    void OnEntry();
    void OnExit();
    void OnException(Exception exception);
}

I guess the MethodDecoratorEx.Fody package has to be updated

Now the real problem
I would like to open an issue/contribute on it´s fork @alexeysuvorov fork ( i.e MethodDecoratorEx.Fody) but it seems not to allow this.

I know post sharp(and it´s price), but being a big Python(decorators) fan but a .NET developer i´ve always wanted C# to have such capabilities without the overly complex CQRS ICommandHandler pattern well explained by "Famous" Steven

Usage a little confusing

I might just confirm here that the README is a little confusing, perhaps I can submit a change... Maybe I'm just stupid.

The "Your Code" section uses methods that, to the unsuspecting reader, seem to come from nowhere -> TestMessages.Record()

And further, those lines of code aren't in the "Compiled Output" - which kind of means they get deleted for some reason.

It also doesn't explain how the MethodDecorator finds your methods.
The other Fody addin I've used, used an attribute. Or it would at least make sense if the IMethodInterceptor interface was supplied... there's probably a good reason not to do that, but would be nice to read it.

I gather someone's just copied/pasted a unit test in there without worrying too much about it.
But if you confirm I've got a point worth making, I'll have a go at it.

Interception

There seems to be no way to actually intercept a method invocation (which I rather expected :/). Is there any reason for that? If not, and you agree on doing this, I could make a PR as soon as I have some time.

By interception I'm talking about something like this: http://doc.postsharp.net/method-interception

Should have method arguments

The methods "before" and "after" have MethodInfo parameters which helps with getting the name and signature of the original method but also original method arguments are important so could you improve this cool plugin to read original method parameters.
Thanks

Change parameters

Можно ли изменить значения параметров из args?

Допустим, пользователь прислал определенный заполненный список параметров, но мне необходимо при возникновении ошибки в базовом методе, переопределить некоторые значения и запустить метод еще раз.

Заранее спасибо!

Can Fody be used for handling exceptions?

Not actually an issue, more of a question, but I wasn't sure where else to ask.

We have a mature WPF desktop application that has a central global exception handler, which we hook up by doing the following in the Application_Statrtup event of App...

Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException;

Our CEO suggested to me that we should be using the Fody method decorator to handle the exceptions instead.

I've looked through the sample code here, and done some searching, but I can't see any particular advantage of using Fody in this way.

In particular, one problem we have been addressing is that exception handling like the above breaks the flow of execution, meaning that the code in CurrentDispatcherUnhandledException() doesn't know the context of how the exception was raised, so can't make an intelligent decision about what to do next. The CEO seemed to think that Fody could help here.

Anyone able to enlighten me?

Build Error after adding MethodDecorator.Fody to the project

Error Fody: The weaver assembly 'MethodDecorator.Fody, Version=0.9.0.4, Culture=neutral, PublicKeyToken=null' references an out of date version of Mono.Cecil.dll 0.9.6.0. At least version 0.10 is expected. The weaver needs to add a NuGet reference to FodyCecil version 3.0.

After Installing MethodDecorator.Fody from Nuget I am getting above error. Please suggest me How to fix this issue? Thanks in advance..

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.