1

I need to apply an attribute (obfuscation related) to all classes in a certain namespace. I'm currently working through the list and doing it by hand, but I'd prefer to do it in a way that it is applied automatically. This would save me some work, but also would ensure that classes added to this namespace in the future will have the attribute as well.

Does C# have any provisions along these lines?

3
  • You can't apply an attribute to a namespace. You can apply it to an entire assembly, although your attribute would have to accept that target, and your obfuscation library would have to know how to interpret that. If it doesn't support that, you might try writing a batch script to modify the .cs files in the project.
    – p.s.w.g
    Nov 11, 2014 at 21:29
  • 3
    @DJKRAZE, what does list<t>.Contains() method has to do with atteributes?
    – Rahul
    Nov 11, 2014 at 21:29
  • I posted the wrong link let me edit that sorry Attributes Tutorial
    – MethodMan
    Nov 11, 2014 at 21:33

1 Answer 1

3

I'm not aware of any built-in facility in .Net that can do it, but you can write one yourself easily using Mono.Cecil here is a method which can inject specified attribute in designated types.

    private static void InjectAttribute<T>(string source,string destination,string nameSpace="")where T:Attribute
    {
        var assembly = AssemblyDefinition.ReadAssembly(source);
        var module = assembly.MainModule;
        var types = module.GetTypes();


        var attributeConstructor = module.Import(typeof (T).GetConstructor(Type.EmptyTypes));

        foreach (var type in types)
        {
            if (type.FullName.StartsWith(nameSpace))
                type.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
        }

        assembly.Write(destination);
    }

and here is a sample Injector Program: (NOTE: I referenced Obfuscate library from my injector program so there is no need to resolve the type for Cecil) :

    private static void Main(string[] args)
    {
        //NOTE:obfuscatelib is already referenced to injector so no need to resolve types
        InjectAttribute<ObfuscationLib.ObfuscateAttribute>(@"assembly path",
            @"injected assembly path","namespace (based on full name)");
    }

you can obtain Mono.Cecil through PM> Install-Package Mono.Cecil Nuget command.

1
  • 1
    It's a nice walkthrough solution
    – Disposer
    Nov 17, 2014 at 20:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.