I want to iterate thru the set of attributes for an entity and for each one, get the text value. I can do this by getting the attribute type and explicit casting but is there a way to do it regardless of type? Similar to this method...
I don't think you'll be able to simply get a text value without testing for and handling the specific field types that are possible on an entity, since some field types have more complex values where you'll need to decide what value you want to get from the field. I ran into this same situation and ended up building a function to do the heavy lifting for me. Basically I did a case statement on the attribute type and got the values I wanted based on the business needs, here's an example of the function I used:
Private Function GetAttributeValue(ByRef pEntity As Entity, ByRef pAttr As KeyValuePair(Of String, Object)) As String
Dim lstrValue As String = String.Empty
Select Case pAttr.Value.GetType
Case GetType(OptionSetValue)
lstrValue = String.Format("{0} - {1}", CType(pAttr.Value, OptionSetValue).Value.ToString(), pEntity.FormattedValues(pAttr.Key))
Case GetType(EntityReference)
lstrValue = CType(pAttr.Value, EntityReference).Id.ToString()
'... could also get the Name value from the EntityReference
Case GetType(Money)
lstrValue = CType(pAttr.Value, Money).Value.ToString()
Case GetType(Date)
lstrValue = CType(pAttr.Value, Date).ToString("MM/dd/yy hh:mm:ss")
Case GetType(Guid)
lstrValue = CType(pAttr.Value, Guid).ToString()
Case Else
'... assume a string and just return the attribute value, or do some other handling
End Select
Return lstrValue
End Function
Once I had this function, I could just iterate through the attributes on the entity I was dealing with and get some text value back that represented the value for each field regardless of the field type. One thing to note, in my example I'm getting the string value of OptionSet
fields using .FormattedValues()
, I believe you can only use that if your entities have the Id
unique identifier field populated.