/JTacticalSim.DataContext/Utility.cs
C# | 90 lines | 66 code | 12 blank | 12 comment | 4 complexity | ec5f53b471767a7ba17f4a2a670208ac MD5 | raw file
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Linq;
- using System.Reflection;
- using System.Xml.Linq;
- using JTacticalSim.API;
- using JTacticalSim.API.Game;
- using JTacticalSim.API.Component;
-
-
- namespace JTacticalSim.DataContext
- {
- public static class Utility
- {
- public static IGame TheGame = Game.Instance;
- public static DataFactory DataFactory = DataFactory.Instance;
-
- public static DataSourceType GetDataSourceType()
- {
- var dataSourceType = ConfigurationManager.AppSettings["datasourcetype"];
-
- switch (dataSourceType)
- {
- case "memory":
- return DataSourceType.MEMORY;
- case "rdbms":
- return DataSourceType.SQL;
- case "XML":
- return DataSourceType.XML;
- default:
- return DataSourceType.UNKNOWN;
- }
- }
-
- public static Type GetDataFileType()
- {
- switch (GetDataSourceType())
- {
- case DataSourceType.XML:
- return typeof(XDocument);
- default:
- throw new Exception("DataSourceType not configured or configured type is not a file type");
- }
- }
-
- /// <summary>
- /// Returns all context table objects with the TableRecognizable attribute
- /// </summary>
- /// <returns></returns>
- public static IEnumerable<KeyValuePair<Type, Tuple<Type, object>>> GetAllTableInfos()
- {
- var tables = new Dictionary<Type, Tuple<Type, object>>();
-
- using (var ctx = DataFactory.GetDataContext())
- {
- PropertyInfo[] props = typeof(BaseDataContext).GetProperties();
-
- foreach (PropertyInfo p in props)
- {
- var attr = Attribute.GetCustomAttribute(p, typeof(TableRecognizable), false) as TableRecognizable;
- if (attr == null) continue;
- tables.Add(attr.RecordType, new Tuple<Type, object>(p.PropertyType.GetGenericArguments().First(),
- p.GetValue(ctx, null)));
- }
- }
-
- return tables;
- }
-
- /// <summary>
- /// Returns tableInfo object for given type
- /// </summary>
- /// <returns></returns>
- public static object GetComponentTable(IBaseComponent component)
- {
- return GetAllTableInfos().SingleOrDefault(ti => component.GetType().GetInterfaces().Contains(ti.Key)).Value.Item2;
- }
-
- /// <summary>
- /// Returns tableInfo object for given type
- /// </summary>
- /// <returns></returns>
- public static object GetComponentTable(Type type)
- {
- return GetAllTableInfos().SingleOrDefault(ti => ti.Key.Equals(type)).Value.Item2;
- }
-
- }
- }