PageRenderTime 46ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/JTacticalSim.DataContext/Utility.cs

https://github.com/Queztionmark/JTacticalSim
C# | 90 lines | 66 code | 12 blank | 12 comment | 4 complexity | ec5f53b471767a7ba17f4a2a670208ac MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Xml.Linq;
  7. using JTacticalSim.API;
  8. using JTacticalSim.API.Game;
  9. using JTacticalSim.API.Component;
  10. namespace JTacticalSim.DataContext
  11. {
  12. public static class Utility
  13. {
  14. public static IGame TheGame = Game.Instance;
  15. public static DataFactory DataFactory = DataFactory.Instance;
  16. public static DataSourceType GetDataSourceType()
  17. {
  18. var dataSourceType = ConfigurationManager.AppSettings["datasourcetype"];
  19. switch (dataSourceType)
  20. {
  21. case "memory":
  22. return DataSourceType.MEMORY;
  23. case "rdbms":
  24. return DataSourceType.SQL;
  25. case "XML":
  26. return DataSourceType.XML;
  27. default:
  28. return DataSourceType.UNKNOWN;
  29. }
  30. }
  31. public static Type GetDataFileType()
  32. {
  33. switch (GetDataSourceType())
  34. {
  35. case DataSourceType.XML:
  36. return typeof(XDocument);
  37. default:
  38. throw new Exception("DataSourceType not configured or configured type is not a file type");
  39. }
  40. }
  41. /// <summary>
  42. /// Returns all context table objects with the TableRecognizable attribute
  43. /// </summary>
  44. /// <returns></returns>
  45. public static IEnumerable<KeyValuePair<Type, Tuple<Type, object>>> GetAllTableInfos()
  46. {
  47. var tables = new Dictionary<Type, Tuple<Type, object>>();
  48. using (var ctx = DataFactory.GetDataContext())
  49. {
  50. PropertyInfo[] props = typeof(BaseDataContext).GetProperties();
  51. foreach (PropertyInfo p in props)
  52. {
  53. var attr = Attribute.GetCustomAttribute(p, typeof(TableRecognizable), false) as TableRecognizable;
  54. if (attr == null) continue;
  55. tables.Add(attr.RecordType, new Tuple<Type, object>(p.PropertyType.GetGenericArguments().First(),
  56. p.GetValue(ctx, null)));
  57. }
  58. }
  59. return tables;
  60. }
  61. /// <summary>
  62. /// Returns tableInfo object for given type
  63. /// </summary>
  64. /// <returns></returns>
  65. public static object GetComponentTable(IBaseComponent component)
  66. {
  67. return GetAllTableInfos().SingleOrDefault(ti => component.GetType().GetInterfaces().Contains(ti.Key)).Value.Item2;
  68. }
  69. /// <summary>
  70. /// Returns tableInfo object for given type
  71. /// </summary>
  72. /// <returns></returns>
  73. public static object GetComponentTable(Type type)
  74. {
  75. return GetAllTableInfos().SingleOrDefault(ti => ti.Key.Equals(type)).Value.Item2;
  76. }
  77. }
  78. }