How do I use Refelection to get names and values of an object

 

Function GetWODataAsMessage(WO AsInteger) AsString

‘#1446
SetContext()

Dim result = (From w In context.WorkOrders Where w.WO = WO Select w).FirstOrDefault

If result IsNothing Then

Return String.Concat(“WO, “, WO, ” was not found”)

EndIf

Dim msg = String.Concat(“Information for W-“, WO)

ForEach prop In result.GetType().GetProperties

If prop.CanRead Then

SelectCase prop.PropertyType

CaseGetType(Byte()), GetType(Business.EBC.EntityModel.Product)

‘Do Nothing

‘Case GetType(Business.EBC.EntityModel.Product)

‘ ‘Do Nothing

Case Else

Dim Tabs = String.Concat(vbTab, vbTab)

If prop.Name.Length < 4 Then

Tabs = String.Concat(vbTab, vbTab, vbTab)

ElseIf prop.Name.Length > 16 Then

Tabs = vbTab

EndIf

‘, prop.PropertyType ‘Testing only

msg = String.Concat(msg, vbCrLf, prop.Name, Tabs, prop.GetValue(result, Nothing))

End Select

EndIf

Next

Return msg

End Function

Advertisements

How do I … use Reflection to build a project that will inspect/analyse other assemblies

For instance:

  • My preference is that TableAdapters are not in the component tray of forms, but ideally in a DAL, or if not that good then in a using part of the forms code. I have always struggled to find these. I want a Reflection utility that will find these

Key reflection code snippets to do this are:

How do I … use reflection to load an Assembly at runtime

Dim asm = System.Reflection.Assembly.LoadFrom(AssemblyFileName)

or

Dim asm = System.Reflection.Assembly.GetExecutingAssembly

How do I … loop around forms of a Loaded assembly

ForEach t1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

Me.ListBox1.Items.Add(String.Concat(t1.Name))

Next

How do I … loop around forms and GetFields

For Each f1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

For Each prop In f1.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).Where(Function(f) f.Name.ToLower.Contains(FieldName))

Me.ListBox1.Items.Add(String.Concat(f1.Name, “: “, prop.Name, “: “, prop.FieldType.Name))

Next

Next

 

How do I .. use Reflection to get the values of an Enum at runtime

Thanks to:
http://www.vb-helper.com/howto_net_list_enum.html

Module Module1

Sub Main()

ForEach field As System.Reflection.FieldInfoInGetType(TestEnum).GetFields.Where(Function(f) f.IsLiteral)
  ‘Console.WriteLine(field.Name + vbTab + CInt(field.GetValue(Nothing)).ToString)
  Console.WriteLine(CInt(field.GetValue(Nothing)).ToString + ” “ + field.Name)
Next
Console.ReadLine()

End Sub

End Module

Public Enum TestEnum
  Cheese = 1
Wallace
Grommit
Wheelbarrows
End Enum