Modules/Jobs/EDMI/ZUGFeRD/PropertyValues.vb
2019-05-09 17:07:53 +02:00

93 lines
2.7 KiB
VB.net

Imports System.Collections.Generic
Imports System.Reflection
Imports System.Text.RegularExpressions
Public Class PropertyValues
Private Shared _indexPattern = "\((\d+)\)"
Private Shared _indexRegex As New Regex(_indexPattern)
Public Shared Function GetPropValues(Obj As Object, PropertyName As String)
End Function
Public Shared Function GetPropValue(Obj As Object, PropertyName As String, Optional ReturnWhenEmpty As Boolean = True)
Dim oNameParts As String() = PropertyName.Split("."c)
If IsNothing(Obj) Then
Return Nothing
End If
If oNameParts.Length = 1 Then
Return Obj.GetType().GetProperty(PropertyName).GetValue(Obj, Nothing)
End If
For Each oPart As String In oNameParts
Dim oType As Type = Obj.GetType()
Dim oPartName = oPart
Dim oIndex As Integer = Nothing
Dim oHasIndex As Boolean = HasIndex(oPartName)
If oHasIndex Then
oPartName = StripIndex(oPart)
oIndex = GetIndex(oPart)
End If
Dim oInfo As PropertyInfo = oType.GetProperty(oPartName)
If IsNothing(oInfo) Then
Return Nothing
End If
If IsNothing(oInfo.GetValue(Obj, Nothing)) Then
Return Nothing
End If
Obj = oInfo.GetValue(Obj, Nothing)
If oHasIndex Then
Obj = Obj(0)
End If
If IsArray(Obj) And Not oHasIndex Then
Dim oCurrentPart = oPart
Dim oPathFragment = PropertyName.
Split(New String() {"." & oCurrentPart & "."}, StringSplitOptions.None)
Dim oResults As New List(Of Object)
For Each oArrayItem In Obj
Dim oResult = GetPropValue(oArrayItem, oPathFragment(1), ReturnWhenEmpty:=False)
If Not IsNothing(oResult) Then
oResults.Add(oResult)
End If
Next
Return oResults
End If
Next
Return Obj
End Function
Private Shared Function GetIndex(Prop As String) As Integer
If Regex.IsMatch(Prop, _indexPattern) Then
Dim oMatch = _indexRegex.Match(Prop)
Dim oGroup = oMatch.Groups.Item(1)
Dim oValue = oGroup.Value
Return Integer.Parse(oValue)
End If
Return Nothing
End Function
Private Shared Function StripIndex(Prop As String) As String
Return Regex.Replace(Prop, _indexPattern, "")
End Function
Private Shared Function HasIndex(Prop As String) As Boolean
Return Regex.IsMatch(Prop, _indexPattern)
End Function
End Class