Friday, February 8, 2013

RESTful Web.API Services Are So Primitive, Man!

A couple quick and dirty tips from the trenches on how to validate primitive types that map to enums of collections (specifically a list). This has come in handy as I develop a new RESTful Web.API .

First up, Enum.TryParse is now supported by the .NET Framework 4.5. So we can now easily validate a  string to make sure it correctly maps to an existing enum value.

 MyEnum matchingEnumValue;  
 if (!Enum.TryParse(enumValueAsString, true, out matchingEnumValue))  
   throw new ArgumentException(enumValueAsString + " is not a valid enum value.");  

Next up, we want to pass in a delimited string of integer values (e.g. "1|2|3"), and parse that into a collection.

 List<int> integerInList;  
   integerInList = integersInString.Split('|').Select(int.Parse).ToList();  
 catch (Exception ex)  
   throw new ArgumentException("Could not parse list of integers. " + ex.Message);  
 if (integerInList == null || integerInList.Count == 0)  
   throw new ArgumentException("Integer list is empty.");  

Easy as bullseye'ing womp rats in my T-16 back home. Share & Enjoy!