Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssemblyInfo and custom attributes

I'd like to add custom attributes to the AssemblyInfo, and I've created an extension class named AssemblyMyCustomAttribute

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyMyCustomAttribute : Attribute
{
    private string myAttribute;

    public AssemblyMyCustomAttribute() : this(string.Empty) { }
    public AssemblyMyCustomAttribute(string txt) { myAttribute = txt; }
}

Then I've added reference to the class in the AssemblyInfo.cs and added the value

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("My Project")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("My Project")]
[assembly: AssemblyMyCustomAttribute("testing")]
[assembly: AssemblyCopyright("Copyright ©  2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

Now I would like to get the value ("testing") in a razor view

I've tried the following with no success:

@ViewContext.Controller.GetType().Assembly.GetCustomAttributes(typeof(AssemblyMyCustomAttribute), false)[0].ToString();

Not sure if this is the best approach, to add custom attributes to my AssemblyInfo. I can't seem to find the correct method to get the value of the attribute.

like image 593
Kman Avatar asked Feb 17 '16 10:02

Kman


People also ask

What are the attributes of Assemblyinfo CS file?

The attributes include title, description, default alias, and configuration. The following table shows the assembly manifest attributes defined in the System. Reflection namespace.

What is net assemblies and attributes?

NET assembly. Assembly attributes are grouped as follows: Identity Attributes – Determine the identity of an assembly: name, version, culture and flags. Informational Attributes – Provide additional information about an assembly: company name, product name, copyright, trademark, and file version.

Which among the following Cannot be target for a custom attribute?

Custom attribute cannot be applied to an assembly.


1 Answers

You need to provide a public member that exposes what you want to display:

[AttributeUsage(AttributeTargets.Assembly)]
public class AssemblyMyCustomAttribute : Attribute
{
    public string Value { get; private set; }

    public AssemblyMyCustomAttribute() : this("") { }
    public AssemblyMyCustomAttribute(string value) { Value = value; }
}

Then cast the attribute and access the member:

var attribute = ViewContext.Controller.GetType().Assembly.GetCustomAttributes(typeof(AssemblyMyCustomAttribute), false)[0];

@(((AssemblyMyCustomaAttribute)attribute).Value)
like image 200
CodeCaster Avatar answered Sep 18 '22 10:09

CodeCaster