using System; using System.Collections.Generic; using System.Reflection; using System.IO; using org.hwo.contracts; namespace org.budnhead.tools { public static class ResourceLibrary { static Dictionary> resourceTypes = new Dictionary>(); static List resourcePaths = new List(new string[]{"."}); static Dictionary prefixes = new Dictionary(); static Dictionary suffixes = new Dictionary(); internal static bool initializeResourceType(Type t,string prefix,string suffix,bool initializeBases){ ConstructorInfo ci = null; new BooleanConditional() .requiresValid(ref ci,delegate { return t.GetConstructor(new Type[]{ typeof(Stream) }); }) .does( delegate { initializeResourceType(t,prefix,suffix); } ); if (initializeBases && (t.BaseType != null)){ initializeResourceType(t.BaseType,prefix,suffix,true); } return true; } internal static bool initializeResourceType(Type t,string prefix,string suffix){ if (prefix != null) prefixes.Add(t,prefix); if (suffix != null) suffixes.Add(t,suffix); return true; } static T findLoadedInstance(string name){ if (resourceTypes.ContainsKey(typeof(T))){ if (resourceTypes[typeof(T)].ContainsKey(name)){ return (T)resourceTypes[typeof(T)][name]; } } throw new KeyNotFoundException(""); } public static void cacheInstance(string name,T instance){ if (!resourceTypes.ContainsKey(typeof(T))){ resourceTypes.Add(typeof(T),new Dictionary()); } resourceTypes[typeof(T)].Add(name,instance); } public static T getResource(string name){ try { return findLoadedInstance(name); } catch (KeyNotFoundException){ string p="",s=""; if (prefixes.ContainsKey(typeof(T))){ p = prefixes[typeof(T)]; } if (suffixes.ContainsKey(typeof(T))){ s = suffixes[typeof(T)]; } string resFileName = FileHelper.findFile(String.Format("{0}{1}{2}",p,name,s),resourcePaths.ToArray()); if (resFileName != null){ Stream resStream = new FileStream(resFileName,FileMode.Open); ConstructorInfo ci = typeof(T).GetConstructor(new Type[]{ typeof(Stream) }); T o = (T)ci.Invoke(new object[]{ resStream }); cacheInstance(name,o); return o; } throw new KeyNotFoundException(String.Format("ResourceLibrary[{0}:{1}]",typeof(T).ToString(),name)); } } } }