Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.33 KB | None | 0 0
  1. using System.ComponentModel; // for DescriptionAttribute
  2.  
  3. enum FunkyAttributesEnum
  4. {
  5. [Description("Name With Spaces1")]
  6. NameWithoutSpaces1,
  7. [Description("Name With Spaces2")]
  8. NameWithoutSpaces2
  9. }
  10.  
  11. Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
  12. foreach (int value in values)
  13. Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);
  14.  
  15. var type = typeof(FunkyAttributesEnum);
  16. var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
  17. var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
  18. var description = ((DescriptionAttribute)attributes[0]).Description;
  19.  
  20. public static class EnumHelper
  21. {
  22. /// <summary>
  23. /// Gets an attribute on an enum field value
  24. /// </summary>
  25. /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
  26. /// <param name="enumVal">The enum value</param>
  27. /// <returns>The attribute of type T that exists on the enum value</returns>
  28. /// <example>string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;</example>
  29. public static T GetAttributeOfType<T>(this Enum enumVal) where T:System.Attribute
  30. {
  31. var type = enumVal.GetType();
  32. var memInfo = type.GetMember(enumVal.ToString());
  33. var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
  34. return (attributes.Length > 0) ? (T)attributes[0] : null;
  35. }
  36. }
  37.  
  38. public static Expected GetAttributeValue<T, Expected>(this Enum enumeration, Func<T, Expected> expression)
  39. where T : Attribute
  40. {
  41. T attribute =
  42. enumeration
  43. .GetType()
  44. .GetMember(enumeration.ToString())
  45. .Where(member => member.MemberType == MemberTypes.Field)
  46. .FirstOrDefault()
  47. .GetCustomAttributes(typeof(T), false)
  48. .Cast<T>()
  49. .SingleOrDefault();
  50.  
  51. if (attribute == null)
  52. return default(Expected);
  53.  
  54. return expression(attribute);
  55. }
  56.  
  57. string description = targetLevel.GetAttributeValue<DescriptionAttribute, string>(x => x.Description);
  58.  
  59. using System;
  60. using System.ComponentModel;
  61.  
  62. public static class EnumExtensions {
  63.  
  64. // This extension method is broken out so you can use a similar pattern with
  65. // other MetaData elements in the future. This is your base method for each.
  66. public static T GetAttribute<T>(this Enum value) where T : Attribute {
  67. var type = value.GetType();
  68. var memberInfo = type.GetMember(value.ToString());
  69. var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
  70. return (T)attributes[0];
  71. }
  72.  
  73. // This method creates a specific call to the above method, requesting the
  74. // Description MetaData attribute.
  75. public static string ToName(this Enum value) {
  76. var attribute = value.GetAttribute<DescriptionAttribute>();
  77. return attribute == null ? value.ToString() : attribute.Description;
  78. }
  79.  
  80. }
  81.  
  82. using System.ComponentModel;
  83.  
  84. public enum Days {
  85. [Description("Sunday")]
  86. Sun,
  87. [Description("Monday")]
  88. Mon,
  89. [Description("Tuesday")]
  90. Tue,
  91. [Description("Wednesday")]
  92. Wed,
  93. [Description("Thursday")]
  94. Thu,
  95. [Description("Friday")]
  96. Fri,
  97. [Description("Saturday")]
  98. Sat
  99. }
  100.  
  101. Console.WriteLine(Days.Mon.ToName());
  102.  
  103. var day = Days.Mon;
  104. Console.WriteLine(day.ToName());
  105.  
  106. public static string GetAttributeDescription(this Enum enumValue)
  107. {
  108. var attribute = enumValue.GetAttributeOfType<DescriptionAttribute>();
  109. return attribute == null ? String.Empty : attribute.Description;
  110. }
  111.  
  112. string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description
  113.  
  114. string desc = myEnumVariable.GetAttributeDescription();
  115.  
  116. public static DisplayAttribute GetDisplayAttributesFrom(this Enum enumValue, Type enumType)
  117. {
  118. return enumType.GetMember(enumValue.ToString())
  119. .First()
  120. .GetCustomAttribute<DisplayAttribute>();
  121. }
  122.  
  123. public enum ModesOfTransport
  124. {
  125. [Display(Name = "Driving", Description = "Driving a car")] Land,
  126. [Display(Name = "Flying", Description = "Flying on a plane")] Air,
  127. [Display(Name = "Sea cruise", Description = "Cruising on a dinghy")] Sea
  128. }
  129.  
  130. void Main()
  131. {
  132. ModesOfTransport TransportMode = ModesOfTransport.Sea;
  133. DisplayAttribute metadata = TransportMode.GetDisplayAttributesFrom(typeof(ModesOfTransport));
  134. Console.WriteLine("Name: {0} nDescription: {1}", metadata.Name, metadata.Description);
  135. }
  136.  
  137. Name: Sea cruise
  138. Description: Cruising on a dinghy
  139.  
  140. public static class EnumHelper
  141. {
  142. // Get the Name value of the Display attribute if the
  143. // enum has one, otherwise use the value converted to title case.
  144. public static string GetDisplayName<TEnum>(this TEnum value)
  145. where TEnum : struct, IConvertible
  146. {
  147. var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
  148. return attr == null ? value.ToString().ToSpacedTitleCase() : attr.Name;
  149. }
  150.  
  151. // Get the ShortName value of the Display attribute if the
  152. // enum has one, otherwise use the value converted to title case.
  153. public static string GetDisplayShortName<TEnum>(this TEnum value)
  154. where TEnum : struct, IConvertible
  155. {
  156. var attr = value.GetAttributeOfType<TEnum, DisplayAttribute>();
  157. return attr == null ? value.ToString().ToSpacedTitleCase() : attr.ShortName;
  158. }
  159.  
  160. /// <summary>
  161. /// Gets an attribute on an enum field value
  162. /// </summary>
  163. /// <typeparam name="TEnum">The enum type</typeparam>
  164. /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
  165. /// <param name="value">The enum value</param>
  166. /// <returns>The attribute of type T that exists on the enum value</returns>
  167. private static T GetAttributeOfType<TEnum, T>(this TEnum value)
  168. where TEnum : struct, IConvertible
  169. where T : Attribute
  170. {
  171.  
  172. return value.GetType()
  173. .GetMember(value.ToString())
  174. .First()
  175. .GetCustomAttributes(false)
  176. .OfType<T>()
  177. .LastOrDefault();
  178. }
  179. }
  180.  
  181. /// <summary>
  182. /// Converts camel case or pascal case to separate words with title case
  183. /// </summary>
  184. /// <param name="s"></param>
  185. /// <returns></returns>
  186. public static string ToSpacedTitleCase(this string s)
  187. {
  188. //https://stackoverflow.com/a/155486/150342
  189. CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
  190. TextInfo textInfo = cultureInfo.TextInfo;
  191. return textInfo
  192. .ToTitleCase(Regex.Replace(s,
  193. "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 "));
  194. }
  195.  
  196. public static IDictionary<string, int> ToDictionary(this Type enumType)
  197. {
  198. return Enum.GetValues(enumType)
  199. .Cast<object>()
  200. .ToDictionary(v => ((Enum)v).ToEnumDescription(), k => (int)k);
  201. }
  202.  
  203. var dic = typeof(ActivityType).ToDictionary();
  204.  
  205. public static string ToEnumDescription(this Enum en) //ext method
  206. {
  207. Type type = en.GetType();
  208. MemberInfo[] memInfo = type.GetMember(en.ToString());
  209. if (memInfo != null && memInfo.Length > 0)
  210. {
  211. object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
  212. if (attrs != null && attrs.Length > 0)
  213. return ((DescriptionAttribute)attrs[0]).Description;
  214. }
  215. return en.ToString();
  216. }
  217.  
  218. public enum ActivityType
  219. {
  220. [Description("Drip Plan Email")]
  221. DripPlanEmail = 1,
  222. [Description("Modification")]
  223. Modification = 2,
  224. [Description("View")]
  225. View = 3,
  226. [Description("E-Alert Sent")]
  227. EAlertSent = 4,
  228. [Description("E-Alert View")]
  229. EAlertView = 5
  230. }
  231.  
  232. public static class EnumExtension
  233. {
  234. public static string ToDescription(this System.Enum value)
  235. {
  236. FieldInfo fi = value.GetType().GetField(value.ToString());
  237. var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  238. return attributes.Length > 0 ? attributes[0].Description : value.ToString();
  239. }
  240. }
  241.  
  242. public static TAttribute GetEnumAttribute<TAttribute>(this Enum enumVal) where TAttribute : Attribute
  243. {
  244. var memberInfo = enumVal.GetType().GetMember(enumVal.ToString());
  245. return memberInfo[0].GetCustomAttributes(typeof(TAttribute), false).OfType<TAttribute>().FirstOrDefault();
  246. }
  247.  
  248. public static string GetEnumDescription(this Enum enumValue) => enumValue.GetEnumAttribute<DescriptionAttribute>()?.Description ?? enumValue.ToString();
  249.  
  250. public static class EnumHelper
  251. {
  252. /// <summary>
  253. /// Gets an attribute on an enum field value
  254. /// </summary>
  255. /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
  256. /// <param name="enumVal">The enum value</param>
  257. /// <returns>The attribute of type T that exists on the enum value</returns>
  258. /// <example>string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;</example>
  259. public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute
  260. {
  261. var type = enumVal.GetType();
  262. var memInfo = type.GetMember(enumVal.ToString());
  263. IEnumerable<Attribute> attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
  264. return (T)attributes?.ToArray()[0];
  265. }
  266. }
  267.  
  268. public static string ToStringUsingXmlEnumAttribute<T>(this T enumValue)
  269. where T: struct, IConvertible
  270. {
  271. if (!typeof(T).IsEnum)
  272. {
  273. throw new ArgumentException("T must be an enumerated type");
  274. }
  275.  
  276. string name;
  277.  
  278. var type = typeof(T);
  279.  
  280. var memInfo = type.GetMember(enumValue.ToString());
  281.  
  282. if (memInfo.Length == 1)
  283. {
  284. var attributes = memInfo[0].GetCustomAttributes(typeof(System.Xml.Serialization.XmlEnumAttribute), false);
  285.  
  286. if (attributes.Length == 1)
  287. {
  288. name = ((System.Xml.Serialization.XmlEnumAttribute)attributes[0]).Name;
  289. }
  290. else
  291. {
  292. name = enumValue.ToString();
  293. }
  294. }
  295. else
  296. {
  297. name = enumValue.ToString();
  298. }
  299.  
  300. return name;
  301. }
  302.  
  303. public static class Program
  304. {
  305. static void Main(string[] args)
  306. {
  307. // display the description attribute from the enum
  308. foreach (Colour type in (Colour[])Enum.GetValues(typeof(Colour)))
  309. {
  310. Console.WriteLine(EnumExtensions.ToName(type));
  311. }
  312.  
  313. // Get the array from the description
  314. string xStr = "Yellow";
  315. Colour thisColour = EnumExtensions.FromName<Colour>(xStr);
  316.  
  317. Console.ReadLine();
  318. }
  319.  
  320. public enum Colour
  321. {
  322. [Description("Colour Red")]
  323. Red = 0,
  324.  
  325. [Description("Colour Green")]
  326. Green = 1,
  327.  
  328. [Description("Colour Blue")]
  329. Blue = 2,
  330.  
  331. Yellow = 3
  332. }
  333. }
  334.  
  335. public static class EnumExtensions
  336. {
  337.  
  338. // This extension method is broken out so you can use a similar pattern with
  339. // other MetaData elements in the future. This is your base method for each.
  340. public static T GetAttribute<T>(this Enum value) where T : Attribute
  341. {
  342. var type = value.GetType();
  343. var memberInfo = type.GetMember(value.ToString());
  344. var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
  345.  
  346. // check if no attributes have been specified.
  347. if (((Array)attributes).Length > 0)
  348. {
  349. return (T)attributes[0];
  350. }
  351. else
  352. {
  353. return null;
  354. }
  355. }
  356.  
  357. // This method creates a specific call to the above method, requesting the
  358. // Description MetaData attribute.
  359. public static string ToName(this Enum value)
  360. {
  361. var attribute = value.GetAttribute<DescriptionAttribute>();
  362. return attribute == null ? value.ToString() : attribute.Description;
  363. }
  364.  
  365. /// <summary>
  366. /// Find the enum from the description attribute.
  367. /// </summary>
  368. /// <typeparam name="T"></typeparam>
  369. /// <param name="desc"></param>
  370. /// <returns></returns>
  371. public static T FromName<T>(this string desc) where T : struct
  372. {
  373. string attr;
  374. Boolean found = false;
  375. T result = (T)Enum.GetValues(typeof(T)).GetValue(0);
  376.  
  377. foreach (object enumVal in Enum.GetValues(typeof(T)))
  378. {
  379. attr = ((Enum)enumVal).ToName();
  380.  
  381. if (attr == desc)
  382. {
  383. result = (T)enumVal;
  384. found = true;
  385. break;
  386. }
  387. }
  388.  
  389. if (!found)
  390. {
  391. throw new Exception();
  392. }
  393.  
  394. return result;
  395. }
  396. }
  397.  
  398. Dictionary<FunkyAttributesEnum, string> description = new Dictionary<FunkyAttributesEnum, string>()
  399. {
  400. { FunkyAttributesEnum.NameWithoutSpaces1, "Name With Spaces1" },
  401. { FunkyAttributesEnum.NameWithoutSpaces2, "Name With Spaces2" },
  402. };
  403.  
  404. string s = description[FunkyAttributesEnum.NameWithoutSpaces1];
  405.  
  406. [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]
  407. public class EnumDisplayName : Attribute
  408. {
  409. public string Name { get; private set; }
  410. public EnumDisplayName(string name)
  411. {
  412. Name = name;
  413. }
  414. }
  415.  
  416. public static class EnumHelper
  417. {
  418. public static string EnumDisplayName(this HtmlHelper helper,EPriceType priceType)
  419. {
  420. //Get every fields from enum
  421. var fields = priceType.GetType().GetFields();
  422. //Foreach field skipping 1`st fieldw which keeps currently sellected value
  423. for (int i = 0; i < fields.Length;i++ )
  424. {
  425. //find field with same int value
  426. if ((int)fields[i].GetValue(priceType) == (int)priceType)
  427. {
  428. //get attributes of found field
  429. var attributes = fields[i].GetCustomAttributes(false);
  430. if (attributes.Length > 0)
  431. {
  432. //return name of found attribute
  433. var retAttr = (EnumDisplayName)attributes[0];
  434. return retAttr.Name;
  435. }
  436. }
  437. }
  438. //throw Error if not found
  439. throw new Exception("Błąd podczas ustalania atrybutów dla typu ceny allegro");
  440. }
  441. }
  442.  
  443. typeof (PharmacyConfigurationKeys).GetFields()
  444. .Where(x => x.GetCustomAttributes(false).Any(y => typeof(DescriptionAttribute) == y.GetType()))
  445. .Select(x => ((DescriptionAttribute)x.GetCustomAttributes(false)[0]).Description);
  446.  
  447. public static class EnumerationExtension
  448. {
  449. public static string Description( this Enum value )
  450. {
  451. // get attributes
  452. var field = value.GetType().GetField( value.ToString() );
  453. var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );
  454.  
  455. // return description
  456. return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
  457. }
  458. }
  459.  
  460. public static class EnumerationExtension
  461. {
  462. public static string Description( this Enum value )
  463. {
  464. // get attributes
  465. var field = value.GetType().GetField( value.ToString() );
  466. var attributes = field.GetCustomAttributes( false );
  467.  
  468. // Description is in a hidden Attribute class called DisplayAttribute
  469. // Not to be confused with DisplayNameAttribute
  470. dynamic displayAttribute = null;
  471.  
  472. if (attributes.Any())
  473. {
  474. displayAttribute = attributes.ElementAt( 0 );
  475. }
  476.  
  477. // return description
  478. return displayAttribute?.Description ?? "Description Not Found";
  479. }
  480. }
  481.  
  482. public enum ExportTypes
  483. {
  484. [Display( Name = "csv", Description = "text/csv" )]
  485. CSV = 0
  486. }
  487.  
  488. var myDescription = myEnum.Description();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement