ResultHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Text;
  5. using Procurement.Enums;
  6. using Procurement.ViewModel;
  7. namespace Procurement.Helpers
  8. {
  9. public class ResultHelper
  10. {
  11. public static ResultViewModel CreateResult(int row, string msg)
  12. {
  13. ResultCode code = ResultCode.Fail, subCode = ResultCode.BusinessError;
  14. if (row > 0)
  15. {
  16. code = ResultCode.Success;
  17. }
  18. else
  19. {
  20. if (msg == "")
  21. {
  22. subCode = ResultCode.ExistsError;
  23. }
  24. }
  25. return CreateResult(code, null, subCode, msg);
  26. }
  27. public static ResultViewModel CreateResult(ResultCode code = ResultCode.Fail, dynamic data = null, ResultCode subCode = ResultCode.Fail, string subMsg = "")
  28. {
  29. string Msg = GetCustomAttributes(code);
  30. if (code == ResultCode.Success)
  31. {
  32. subCode = code;
  33. subMsg = string.IsNullOrEmpty(subMsg) ? Msg : subMsg;
  34. }
  35. else
  36. {
  37. subMsg = string.IsNullOrEmpty(subMsg) ? GetCustomAttributes(subCode) : subMsg;
  38. }
  39. return new ResultViewModel()
  40. {
  41. Code = Convert.ToInt32(code).ToString(),
  42. Msg = Msg,
  43. SubCode = Convert.ToInt32(subCode).ToString(),
  44. SubMsg = subMsg,
  45. Data = data
  46. };
  47. }
  48. private static string GetCustomAttributes(ResultCode code)
  49. {
  50. Type type = code.GetType();
  51. FieldInfo fieldInfo = type.GetField(code.ToString());
  52. var customAttributes = fieldInfo.GetCustomAttributesData();
  53. if (customAttributes.Count > 0)
  54. {
  55. return customAttributes[0].NamedArguments[0].TypedValue.Value.ToString();
  56. }
  57. return "";
  58. }
  59. }
  60. }