4

I am working on various concepts in PostSharp.

Updated:

This is my program class as

namespace myconstructor
{
    class Program
    {
        static void Main(string[] args)
        {
            createfolder();
            streamfolder();
        }
        public static void createfolder()
        {
            File.Create("E:/samplefile.txt");

        }
        public static void streamfolder()
        {
            StreamWriter sw = new StreamWriter("E:/samplestream.txt");
        }
    }

}

and my aspect class as

1)some tracing aspect class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PostSharp.Extensibility;
using PostSharp.Aspects.Dependencies;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using System.Reflection;
using System.Linq.Expressions;

namespace MyProviders
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Event)]
    [MulticastAttributeUsage(MulticastTargets.Event, AllowMultiple = false)]
    [AspectTypeDependency(AspectDependencyAction.Commute,typeof(SomeTracingAspect))]
    [Serializable]
    public class SomeTracingAspect : EventLevelAspect
    {
        [OnMethodEntryAdvice, MethodPointcut("SelectConstructors")]
        public void OnConstructorEntry(MethodExecutionArgs args)
        {
            args.ReturnValue = "aspectfile"; 
        }

        IEnumerable<ConstructorInfo> SelectConstructors(EventInfo target)
        {
            return target.DeclaringType.GetConstructors(
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
        }

        public override void RuntimeInitialize(EventInfo eventInfo)
        {
            base.RuntimeInitialize(eventInfo);

        }
    }

}

2)TraceAspectProvider class:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using PostSharp.Aspects; using System.Reflection;

namespace MyProviders { public class TraceAspectProvider : IAspectProvider { readonly SomeTracingAspect aspectToApply = new SomeTracingAspect();

    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        Assembly assembly = (Assembly)targetElement;

        List<AspectInstance> instances = new List<AspectInstance>();
        foreach (Type type in assembly.GetTypes())
        {
            ProcessType(type, instances);
        }

        return instances;
    }

    private void ProcessType(Type type, List<AspectInstance> instances)
    {
        foreach (ConstructorInfo target in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
        {
            instances.Add(new AspectInstance(target, aspectToApply));
        }

        foreach (Type nestedType in type.GetNestedTypes())
        {
            ProcessType(nestedType, instances);
        }

} } }

and my aspect file given as

 "C:\Program Files\PostSharp 2.1\Release\postsharp.4.0-x86-cil.exe" "D:\fileaspecttest\myconstructor.exe" /p:AspectProviders=MyProviders.AspectProvider,MyProviders /p:Output="D:\fileaspecttest\myaspect.exe"

i am getting error as

 error PS0125: An unexpected exception occured when executing user code: System.ArgumentNullException: Value cannot be null.
 error PS0125: Parameter name: type
 error PS0125:    at System.Activator.CreateInstance(Type type, Boolean nonPublic)
 error PS0125:    at ^7HtKTJrYMoHj.^kfEQVEmN.^jK8C2yxJ()
 error PS0125:    at PostSharp.Sdk.Utilities.ExceptionHelper.ExecuteUserCode[T](MessageLocation messageLocation, Func`1 userCode, Type[] acceptableExceptions)

Waiting for your solution and responses

GowthamanSS
  • 1,434
  • 4
  • 33
  • 58

1 Answers1

3

I think your main problem is you are trying to apply aspects on 3th party libraries (mscorlib). You can take a look at Dustin's blog post on how to do this which might help you out. Do take into account officially this isn't supported by PostSharp.

In order to apply aspects to a constructor you can probably use a TypeLevelAspect and a MulticastPointcut with its Targets set to e.g. InstanceConstructor.

When you can't use a TypeLevelAspect (e.g. you want to apply the aspect to events) I previously used a OnMethodEntryAdvice and a MethodPointCut. This allows you to search for the constructors manually.

[OnMethodEntryAdvice, MethodPointcut( "SelectConstructors" )]
public void OnConstructorEntry( MethodExecutionArgs args )
{
    ...
}

IEnumerable<ConstructorInfo> SelectConstructors( EventInfo target )
{
    return target.DeclaringType.GetConstructors(
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
}

A more extended discussion how I applied this to initialize events from the constructor can be found on my blog.

The latest complete source code of this class can be found on github. I've made several changes since the blog post, but the principle of targeting constructors remains the same.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161
  • can i just replace your code SelectConstructors in [OnMethodEntryAdvice, MethodPointcut( "SelectConstructors" )] with StreamWriter in order to solve my problem – GowthamanSS Nov 15 '12 at 06:19
  • @GowthamanSS I'm not 100% sure you will be able to adjust the arguments, I suggest you try it, but within the `OnConstructorEntry()` method you define the code which needs to be injected at the start of the constructor. You can access the constructor arguments through `args.Arguments`. – Steven Jeuris Nov 15 '12 at 16:34
  • Additionally, be sure to check out my update. Probably applying aspects to a 3th party library isn't a good idea. – Steven Jeuris Nov 15 '12 at 16:56
  • for the past two days i tried your code but i did not get the correct way or solution as if my dll has more than one constructor there by how can i proceed – GowthamanSS Nov 20 '12 at 11:32
  • can you provide me some sample code which solves my above problem which will be useful for me to proceed – GowthamanSS Nov 20 '12 at 11:33
  • @GowthamanSS Did you read my update and Dustin's article? Additionally, please update your question with relevant errors you are getting. Right now you provide little information to go forth on. – Steven Jeuris Nov 20 '12 at 12:14
  • based on my understanding i have provided solution and updated the above as per your request – GowthamanSS Nov 20 '12 at 14:01