Question

I have created a custom attribute and use it in the AssemblyInfo.vb file. The attribute is declared in another file like so:

Public NotInheritable Class AssemblyBuildNameAttribute
    Inherits Attribute

    Private _p1 As String

    Sub New(p1 As String)
        ' TODO: Complete member initialization 
        _p1 = p1
    End Sub

End Class

And is in the AssemblyInfo.vb file like so:

<Assembly: AssemblyVersion("0.4.15")> 
<Assembly: AssemblyFileVersion("13.10.1.8")> 
<Assembly: AssemblyBuildName("alpha")>

How can I call this custom attribute?? I would like to be able to call it just like I call the version information like so:

Public Class AppInfo
  Public Shared Function VersionMajor() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Major.ToString()
  End Function
  Public Shared Function VersionMinor() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString()
  End Function
  Public Shared Function VersionPatch() As String
    Return Assembly.GetExecutingAssembly().GetName().Version.Build.ToString()
  End Function
End Class
Was it helpful?

Solution

You have to use Reflection to get attribute information and value, and you will need one proc for each attribute.

First though, your sample Attribute class is missing a key item: HOW TO RETURN the info. You need to add a property getter:

Friend ReadOnly GetBuild() As String
   Get
      Return _p1
   End Get
End Property

NOW you are ready

Friend Function GetAsmBuild() As String
    Dim assy As [Assembly] = [Assembly].GetExecutingAssembly
    Dim Attributes As Object()


    Attributes = assy.GetCustomAttributes(GetType(AssemblyBuildNameAttribute), False)
    If Attributes.Length > 0 Then
        Return Attributes(0).GetBuild
    Else
       Return String.Empty
    End If

 End Function

GetVersion is the name of the Property getter. So for the one I added it would be:

Return Attributes(0).GetBuild

It is about the same as getting Attr for Classes or Enums etc. Also: Assemblies already have a version and such you can control in the Project properties settings. And procs already exist in System.Reflection to return them.

Edit:

The way to get the info at runtime:

Public Shared Function VersionPatch() As String
    Return GetAsmBuild
 End Function

or name my proc VersionPatch

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top