Konzy262
Konzy262

Reputation: 3097

Linq to scan an assembly for a method with a particular attribute and attribute property

I'm attempting to write a linq statement that will scan the entire executing assembly for a method that has a particular attribute and a particular attribute property value.

This is my attribute...

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class ScenarioSetup : Attribute
{
    public string ScenarioTitle { get; set; }

    public bool ActiveForBuild { get; set; }
}

And this is an example of a method that uses it....

[ScenarioSetup(ScenarioTitle = "R/S/T [Assessor Management] ASM.08 - Activate Assessor", ActiveForBuild = true)]
public void CreateInactiveAssessor()
{
    var assessor = ApiHelper.PostRequest(AssessorFactory.CreateAssessorApi("Woodwork"), Client, false);

    AddStateItem(assessor, StateItemTag.AssessorEntity);
}

So using the example above, I would like to use reflection to find the method with the [ScenarioSetup] attribute, then check whether that attributes ScenarioTitle equals a certain value (in this case 'R/S/T [Assessor Management] ASM.08 - Activate Assessor')

This is what I have so far...

var methodz = Assembly.GetExecutingAssembly().GetTypes()
            .SelectMany(t => t.GetMethods())
            .Where(m => m.GetCustomAttributes(typeof(ScenarioSetup), false).Length > 0);

I then get lost trying to do the ScenarioTitle check.

Can anyone help?

Upvotes: 0

Views: 170

Answers (2)

Lucian Bumb
Lucian Bumb

Reputation: 2881

Another way is:

`

var methods = Assembly.GetExecutingAssembly()
.GetTypes()
.SelectMany(t => t.GetMethods())
.Where(m => m.GetCustomAttributes<ScenarioSetupAttribute>().Any())
.Where(x=>x.GetCustomAttribute<ScenarioSetupAttribute>().ScenarioTitle=="R/S/T [Assessor Management] ASM.08 - Activate Assessor");`

Upvotes: 1

rahulaga-msft
rahulaga-msft

Reputation: 4164

You can try :

var methodz = Assembly.GetExecutingAssembly().GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(ScenarioSetupAttribute), false)
                      .Cast<ScenarioSetupAttribute>().Where(a=>a.ScenarioTitle=="R/S/T [Assessor Management] ASM.08 - Activate Assessor").Length > 0);

Upvotes: 1

Related Questions