For what it's worth, this is the helper class that Shipping Director uses support its Custom Customer Attribute Extensions:
GetAttributeValues(this Customer customer, string attributeName, string valueSeparator)
GetAttributeValues(this Customer customer, string attributeName)
HasAttributeValue(this Customer customer, string attributeName, string valueName)
HasAttributeValue(this Customer customer, string attributeName)
HasAttributeValue(this Customer customer, int valueId)
-It's in an Extension class, so it uses Resolve<ICustomerAttributeService> rather than the DI'd service.
-Internally, it uses a helper class (rather than Dictionary like yours), so that it also has the Value Id. (Because value text might be localized, or store owner might change the text - the attribute Id never changes.)
// helper class
private class AttributeValuePair
{
public string AttributeName { get; set; }
public int ValueId { get; set; }
public string ValueText { get; set; }
}
-I decided to do my own XDocument.Parse ( I forget why, but I think because the core Parse did not look optimal for my purpose)
private static IList<AttributeValuePair> GetSelectedAttributes(Customer customer)
{
if (customer == null)
return null;
string selectedCustomerAttributes = customer.GetAttribute<string>(SystemCustomerAttributeNames.CustomCustomerAttributes);
var attributeValueList = new List<AttributeValuePair>();
if (String.IsNullOrWhiteSpace(selectedCustomerAttributes))
return attributeValueList;
var _customerAttributeService = Nop.Core.Infrastructure.EngineContext.Current.Resolve<Nop.Services.Customers.ICustomerAttributeService>();
var customerAttributes = _customerAttributeService.GetAllCustomerAttributes();
XDocument doc = XDocument.Parse(selectedCustomerAttributes);
var selectedAttributes = doc.Root.Descendants("CustomerAttribute");
foreach (var selectedAttribute in selectedAttributes)
{
int selectedId = int.Parse(selectedAttribute.Attributes("ID").First().Value);
foreach (var value in selectedAttribute.Descendants("CustomerAttributeValue").Elements("Value"))
{
var customerAttribute = customerAttributes.Single(pva => pva.Id == selectedId);
switch (customerAttribute.AttributeControlType)
{
case AttributeControlType.DropdownList:
case AttributeControlType.RadioList:
case AttributeControlType.Checkboxes:
var productVariantAttributeValue = customerAttribute.CustomerAttributeValues.Single(pvav => pvav.Id == int.Parse(value.Value));
var attributeValue = new AttributeValuePair()
{
AttributeName = customerAttribute.Name,
ValueId = productVariantAttributeValue.Id,
ValueText = productVariantAttributeValue.Name
};
attributeValueList.Add(attributeValue);
break;
default:
attributeValue = new AttributeValuePair()
{
AttributeName = customerAttribute.Name,
ValueId = 0,
ValueText = value.Value
};
attributeValueList.Add(attributeValue);
break;
}
}
}
return attributeValueList;
}