code_junkie

C# String enums

Nov 13th, 2011
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.59 KB | None | 0 0
  1. public enum AuthenticationMethod
  2. {
  3. FORMS = 1,
  4. WINDOWSAUTHENTICATION = 2,
  5. SINGLESIGNON = 3
  6. }
  7.  
  8. public class StringValue : System.Attribute
  9. {
  10. private string _value;
  11.  
  12. public StringValue(string value)
  13. {
  14. _value = value;
  15. }
  16.  
  17. public string Value
  18. {
  19. get { return _value; }
  20. }
  21.  
  22. }
  23.  
  24. public enum AuthenticationMethod
  25. {
  26. [StringValue("FORMS")]
  27. FORMS = 1,
  28. [StringValue("WINDOWS")]
  29. WINDOWSAUTHENTICATION = 2,
  30. [StringValue("SSO")]
  31. SINGLESIGNON = 3
  32. }
  33.  
  34. public static class StringEnum
  35. {
  36. public static string GetStringValue(Enum value)
  37. {
  38. string output = null;
  39. Type type = value.GetType();
  40.  
  41. //Check first in our cached results...
  42.  
  43. //Look for our 'StringValueAttribute'
  44.  
  45. //in the field's custom attributes
  46.  
  47. FieldInfo fi = type.GetField(value.ToString());
  48. StringValue[] attrs =
  49. fi.GetCustomAttributes(typeof(StringValue),
  50. false) as StringValue[];
  51. if (attrs.Length > 0)
  52. {
  53. output = attrs[0].Value;
  54. }
  55.  
  56. return output;
  57. }
  58. }
  59.  
  60. string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
  61.  
  62. public sealed class AuthenticationMethod {
  63.  
  64. private readonly String name;
  65. private readonly int value;
  66.  
  67. public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
  68. public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
  69. public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");
  70.  
  71. private AuthenticationMethod(int value, String name){
  72. this.name = name;
  73. this.value = value;
  74. }
  75.  
  76. public override String ToString(){
  77. return name;
  78. }
  79.  
  80. }
  81.  
  82. private static readonly Dictionary<string, AuthenticationMethod> instance
  83.  
  84. instance[name] = value;
  85.  
  86. public static explicit operator AuthenticationMethod(string str)
  87. {
  88. AuthenticationMethod result;
  89. if (instance.TryGet(str, out result))
  90. return result
  91. else
  92. throw new InvalidCastException();
  93. }
  94.  
  95. Enum.GetName(Type MyEnumType, object enumvariable)
  96.  
  97. Shipper x = Shipper.FederalExpress;
  98. string s = Enum.GetName(typeof(Shipper), x);
  99.  
  100. Console.WriteLine("Auth method: {0}", AuthenticationMethod.Forms.ToString());
  101.  
  102. static string ToFriendlyCase(this string EnumString)
  103. {
  104. return Regex.Replace(EnumString, "(?!^)([A-Z])", " $1");
  105. }
  106.  
  107. Console.WriteLine("ConvertMyCrazyPascalCaseSentenceToFriendlyCase".ToFriendlyCase());
  108.  
  109. public static string GetStringValue(this AuthenticationMethod value)
  110. {
  111. string output = null;
  112. Type type = value.GetType();
  113. FieldInfo fi = type.GetField(value.ToString());
  114. StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
  115. if (attrs.Length > 0)
  116. output = attrs[0].Value;
  117. return output;
  118. }
  119.  
  120. Console.WriteLine(AuthenticationMethod.SSO.GetStringValue());
  121.  
  122. public static string GetName( this MyEnum input ) {
  123. switch ( input ) {
  124. case MyEnum.WINDOWSAUTHENTICATION:
  125. return "Windows";
  126. //and so on
  127. }
  128. }
  129.  
  130. public static string GetDescription<T>(this object enumerationValue)
  131. where T : struct
  132. {
  133. Type type = enumerationValue.GetType();
  134. if (!type.IsEnum)
  135. {
  136. throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
  137. }
  138.  
  139. //Tries to find a DescriptionAttribute for a potential friendly name
  140. //for the enum
  141. MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
  142. if (memberInfo != null && memberInfo.Length > 0)
  143. {
  144. object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
  145.  
  146. if (attrs != null && attrs.Length > 0)
  147. {
  148. //Pull out the description value
  149. return ((DescriptionAttribute)attrs[0]).Description;
  150. }
  151. }
  152. //If we have no description attribute, just return the ToString of the enum
  153. return enumerationValue.ToString();
  154.  
  155. }
  156.  
  157. public enum Cycle : int
  158. {
  159. [Description("Daily Cycle")]
  160. Daily = 1,
  161. Weekly,
  162. Monthly
  163. }
  164.  
  165. public static string ToSimpleString(this enum)
  166. {
  167. switch (enum)
  168. {
  169. case ComplexForms:
  170. return "ComplexForms";
  171. break;
  172. }
  173. }
  174.  
  175. public static string ToFormattedString(this enum)
  176. {
  177. switch (enum)
  178. {
  179. case ComplexForms:
  180. return "Complex Forms";
  181. break;
  182. }
  183. }
  184.  
  185. [TypeConverter(typeof(CustomEnumTypeConverter(typeof(MyEnum))]
  186. public enum MyEnum
  187. {
  188. // The custom type converter will use the description attribute
  189. [Description("A custom description")]
  190. ValueWithCustomDescription,
  191.  
  192. // This will be exposed exactly.
  193. Exact
  194. }
  195.  
  196. public class CustomEnumTypeConverter<T> : EnumConverter
  197. where T : struct
  198. {
  199. private static readonly Dictionary<T,string> s_toString =
  200. new Dictionary<T, string>();
  201.  
  202. private static readonly Dictionary<string, T> s_toValue =
  203. new Dictionary<string, T>();
  204.  
  205. private static bool s_isInitialized;
  206.  
  207. static CustomEnumTypeConverter()
  208. {
  209. System.Diagnostics.Debug.Assert(typeof(T).IsEnum,
  210. "The custom enum class must be used with an enum type.");
  211. }
  212.  
  213. public CustomEnumTypeConverter() : base(typeof(T))
  214. {
  215. if (!s_isInitialized)
  216. {
  217. Initialize();
  218. s_isInitialized = true;
  219. }
  220. }
  221.  
  222. protected void Initialize()
  223. {
  224. foreach (T item in Enum.GetValues(typeof(T)))
  225. {
  226. string description = GetDescription(item);
  227. s_toString[item] = description;
  228. s_toValue[description] = item;
  229. }
  230. }
  231.  
  232. private static string GetDescription(T optionValue)
  233. {
  234. var optionDescription = optionValue.ToString();
  235. var optionInfo = typeof(T).GetField(optionDescription);
  236. if (Attribute.IsDefined(optionInfo, typeof(DescriptionAttribute)))
  237. {
  238. var attribute =
  239. (DescriptionAttribute)Attribute.
  240. GetCustomAttribute(optionInfo, typeof(DescriptionAttribute));
  241. return attribute.Description;
  242. }
  243. return optionDescription;
  244. }
  245.  
  246. public override object ConvertTo(ITypeDescriptorContext context,
  247. System.Globalization.CultureInfo culture,
  248. object value, Type destinationType)
  249. {
  250. var optionValue = (T)value;
  251.  
  252. if (destinationType == typeof(string) &&
  253. s_toString.ContainsKey(optionValue))
  254. {
  255. return s_toString[optionValue];
  256. }
  257.  
  258. return base.ConvertTo(context, culture, value, destinationType);
  259. }
  260.  
  261. public override object ConvertFrom(ITypeDescriptorContext context,
  262. System.Globalization.CultureInfo culture, object value)
  263. {
  264. var stringValue = value as string;
  265.  
  266. if (!string.IsNullOrEmpty(stringValue) && s_toValue.ContainsKey(stringValue))
  267. {
  268. return s_toValue[stringValue];
  269. }
  270.  
  271. return base.ConvertFrom(context, culture, value);
  272. }
  273. }
  274.  
  275. [TypeConverter(typeof(CustomEnumTypeConverter(typeof(MyEnum))]
  276. public enum MyEnum
  277. {
  278. // The custom type converter will use the description attribute
  279. [Description("A custom description")]
  280. ValueWithCustomDescription,
  281. // This will be exposed exactly.
  282. Exact
  283. }
  284.  
  285. [TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
  286. public enum MyEnum
  287. {
  288. // The custom type converter will use the description attribute
  289. [Description("A custom description")]
  290. ValueWithCustomDescription,
  291.  
  292. // This will be exposed exactly.
  293. Exact
  294. }
  295.  
  296. public sealed class FormsAuth
  297. {
  298. public override string ToString{return "Forms Authtentication";}
  299. }
  300. public sealed class WindowsAuth
  301. {
  302. public override string ToString{return "Windows Authtentication";}
  303. }
  304.  
  305. public sealed class SsoAuth
  306. {
  307. public override string ToString{return "SSO";}
  308. }
  309.  
  310. object auth = new SsoAuth(); //or whatever
  311.  
  312. //...
  313. //...
  314. // blablabla
  315.  
  316. DoSomethingWithTheAuth(auth.ToString());
  317.  
  318. public enum AuthenticationMethod
  319. {
  320. FORMS = 1,
  321. WINDOWSAUTHENTICATION = 2,
  322. SINGLESIGNON = 3
  323. }
  324.  
  325. public class MyClass
  326. {
  327. private Dictionary<AuthenticationMethod, String> map = new Dictionary<AuthenticationMethod, String>();
  328. public MyClass()
  329. {
  330. map.Add(AuthenticationMethod.FORMS,"Forms Authentication");
  331. map.Add(AuthenticationMethod.WINDOWSAUTHENTICATION ,"Windows Authentication");
  332. map.Add(AuthenticationMethod.SINGLESIGNON ,"SSo Authentication");
  333. }
  334. }
  335.  
  336. /// <summary>
  337. /// An Enum-like object which carries the string flags used in InternetSecure payment forms.
  338. /// </summary>
  339. [Serializable]
  340. public sealed class PaymentItemFlag : StringEnum
  341. {
  342. private static readonly PaymentItemFlag _testSuccess = new PaymentItemFlag(1, "{TEST}");
  343. private static readonly PaymentItemFlag _testDecline = new PaymentItemFlag(2, "{TESTD}");
  344. private static readonly PaymentItemFlag _recurringBilling = new PaymentItemFlag(3, "{RB}");
  345.  
  346. public static PaymentItemFlag TestSuccess { get { return _testSuccess; } }
  347. public static PaymentItemFlag TestDecline { get { return _testDecline; } }
  348. public static PaymentItemFlag RecurringBilling { get { return _recurringBilling; } }
  349.  
  350. private PaymentItemFlag(int value, string name)
  351. : base(value, name)
  352. { }
  353.  
  354. public static implicit operator PaymentItemFlag(string x)
  355. {
  356. switch (x)
  357. {
  358. case "{TEST}":
  359. return PaymentItemFlag.TestSuccess;
  360. case "{TESTD}":
  361. return PaymentItemFlag.TestDecline;
  362. case "{RB}":
  363. return PaymentItemFlag.RecurringBilling;
  364. default:
  365. return default(PaymentItemFlag);
  366. }
  367. }
  368.  
  369. public static implicit operator PaymentItemFlag(int x)
  370. {
  371. switch (x)
  372. {
  373. case 1:
  374. return PaymentItemFlag.TestSuccess;
  375. case 2:
  376. return PaymentItemFlag.TestDecline;
  377. case 3:
  378. return PaymentItemFlag.RecurringBilling;
  379. default:
  380. return default(PaymentItemFlag);
  381. }
  382. }
  383. }
  384.  
  385. /// <summary>
  386. /// Base class for Enum-like strings
  387. ///
  388. /// Includes equality plumbing in case you're dealing in copies of StringEnums.
  389. /// </summary>
  390. [Serializable]
  391. public abstract class StringEnum : Object
  392. {
  393. protected readonly string _name;
  394. protected readonly int _value;
  395.  
  396. protected StringEnum(int value, string name)
  397. {
  398. _name = name;
  399. _value = value;
  400. }
  401.  
  402. public override string ToString()
  403. {
  404. return _name;
  405. }
  406.  
  407. public static implicit operator string(StringEnum x)
  408. {
  409. return x._name;
  410. }
  411.  
  412. public static implicit operator int(StringEnum x)
  413. {
  414. return x._value;
  415. }
  416.  
  417. public static bool operator ==(StringEnum x, StringEnum y)
  418. {
  419. if (((object)x == null) || ((object)y == null))
  420. {
  421. return false;
  422. }
  423.  
  424. if (Object.ReferenceEquals(x, y))
  425. {
  426. return true;
  427. }
  428.  
  429. return (x._value == y._value);
  430. }
  431.  
  432. public static bool operator !=(StringEnum x, StringEnum y)
  433. {
  434. return !(x._value == y._value);
  435. }
  436.  
  437. public override bool Equals(object obj)
  438. {
  439. StringEnum p = obj as StringEnum;
  440.  
  441. if ((object)p == null)
  442. {
  443. return false;
  444. }
  445.  
  446. return (_value == p._value);
  447. }
  448.  
  449. public bool Equals(StringEnum flag)
  450. {
  451. return (_value == flag._value);
  452. }
  453.  
  454. public override int GetHashCode()
  455. {
  456. return _value.GetHashCode();
  457. }
  458. }
  459.  
  460. PaymentItemFlag fas = "{asdf}"; // fas will be null
  461.  
  462. PaymentItemFlag asd = "{TESTD}"; // asd will be PaymentItemFlag.TestDecline
  463.  
  464. bool equal = (asd == PaymentItemFlag.TestSuccess); // equal will be false
  465.  
  466. bool equal2 = (asd == PaymentItemFlag.TestDecline); // equal2 will be true
  467.  
  468. HashSet<PaymentItemFlag> set = new HashSet<PaymentItemFlag>();
  469.  
  470. set.Add("{asdf}"); // null
  471. set.Add(1); // PaymentItemFlag.TestSuccess
  472. set.Add("{TESTD}"); // PaymentItemFlag.TestDecline
  473.  
  474. foreach (string str in Enum.GetNames(typeof(enumHeaderField)))
  475. {
  476. Debug.WriteLine(str);
  477. }
  478.  
  479. public Type ResourceType { get; private set; }
  480. public string ResourceName { get; private set; }
  481. public int SortOrder { get; private set; }
  482. public EnumResourceAttribute(Type ResourceType,
  483. string ResourceName,
  484. int SortOrder)
  485. {
  486.  
  487. this.ResourceType = ResourceType;
  488. this.ResourceName = ResourceName;
  489. this.SortOrder = SortOrder;
  490. }
  491. }
  492.  
  493. }
  494. return string.Empty;
  495. }
  496.  
  497.  
  498. public static IList GetStrings(this Type enumType)
  499. {
  500. List<string> stringList = new List<string>();
  501. FieldInfo[] fiArray = enumType.GetFields();
  502. foreach (FieldInfo fi in fiArray)
  503. {
  504. EnumResourceAttribute ea =
  505. (EnumResourceAttribute)fi
  506. .GetCustomAttributes(typeof(EnumResourceAttribute), false)
  507. .FirstOrDefault();
  508. if (ea != null)
  509. {
  510. PropertyInfo pi = ea.ResourceType
  511. .GetProperty(CommonConstants.ResourceManager);
  512. if (pi != null)
  513. {
  514. ResourceManager rm = (ResourceManager)pi
  515. .GetValue(null, null);
  516. stringList.Add(rm.GetString(ea.ResourceName));
  517. }
  518. }
  519. }
  520. return stringList.ToList();
  521. }
  522. }
Add Comment
Please, Sign In to add comment