ApiData.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Edge.Core.UniversalApi
  6. {
  7. public abstract class ApiDataBase
  8. {
  9. /// <summary>
  10. /// used to match request and response
  11. /// </summary>
  12. //public Guid Id { get; set; }
  13. }
  14. public class ApiData : ApiDataBase
  15. {
  16. //public IEnumerable<string> Ids { get; set; }
  17. public List<ApiDataParameter> Parameters { get; set; }
  18. //public int IntValue { get; set; }
  19. //public InnerApiData InnerData { get; set; }
  20. }
  21. public class ApiDataParameter
  22. {
  23. public string Name { get; set; }
  24. public string Value { get; set; }
  25. }
  26. public static class ApiDataExtension
  27. {
  28. public static string Get(this ApiData self, string name)
  29. {
  30. return self.Parameters.FirstOrDefault(i => i.Name.ToLower() == name)?.Value;
  31. }
  32. public static TResult Get<TResult>(this ApiData self, string name, TResult defaultValue)
  33. {
  34. var value = self.Parameters.FirstOrDefault(i => i.Name.ToLower() == name)?.Value;
  35. try
  36. {
  37. return ParseType(value, defaultValue);
  38. }
  39. catch(Exception ex)
  40. {
  41. }
  42. return defaultValue;
  43. }
  44. public static bool IsEmpty(this ApiData self)
  45. {
  46. return self.Parameters == null || !self.Parameters.Any();
  47. }
  48. private static TResult ParseType<TResult>(string value, TResult defaultValue) => defaultValue.GetType().Name switch
  49. {
  50. "Boolean" => (TResult)Convert.ChangeType(bool.Parse(value), typeof(TResult)),
  51. "Byte" => (TResult)Convert.ChangeType(byte.Parse(value), typeof(TResult)),
  52. "SByte" => (TResult)Convert.ChangeType(sbyte.Parse(value), typeof(TResult)),
  53. "Decimal" => (TResult)Convert.ChangeType(decimal.Parse(value), typeof(TResult)),
  54. "Double" => (TResult)Convert.ChangeType(double.Parse(value), typeof(TResult)),
  55. "Single" => (TResult)Convert.ChangeType(float.Parse(value), typeof(TResult)),
  56. "Int32" => (TResult)Convert.ChangeType(int.Parse(value), typeof(TResult)),
  57. "UInt32" => (TResult)Convert.ChangeType(uint.Parse(value), typeof(TResult)),
  58. "Int64" => (TResult)Convert.ChangeType(long.Parse(value), typeof(TResult)),
  59. "UInt64" => (TResult)Convert.ChangeType(ulong.Parse(value), typeof(TResult)),
  60. "Int16" => (TResult)Convert.ChangeType(short.Parse(value), typeof(TResult)),
  61. "UInt16" => (TResult)Convert.ChangeType(ushort.Parse(value), typeof(TResult)),
  62. "DateTime" => (TResult)Convert.ChangeType(DateTime.Parse(value), typeof(TResult)),
  63. _ => defaultValue
  64. };
  65. }
  66. }