Advertisement
cheprogrammer

ResourceManager Full

Feb 25th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.08 KB | None | 0 0
  1. /// <summary>
  2. /// Type of serialization
  3. /// Custom means registered ResourceFactory
  4. /// </summary>
  5. public enum FormatterType
  6. {
  7.     Binary, JSON, Custom
  8. }
  9.  
  10. /// <summary>
  11. /// Thread safe Resource Manager for UniqueEntity-based types
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. public static class ResourceManager<T> where T : UniqueEntity
  15. {
  16.     /// <summary>
  17.     /// Default resource directory. (Value: "data")
  18.     /// </summary>
  19.     public static string ResoucePath = "data";
  20.  
  21.     private static object _lock = new object();
  22.  
  23.     /// <summary>
  24.     /// Determines if resources were load or not
  25.     /// </summary>
  26.     public static bool IsLoaded { get; private set; }
  27.  
  28.     /// <summary>
  29.     /// Gets the path and filename for resource
  30.     /// </summary>
  31.     public static string ResourceFilename
  32.     {
  33.         get
  34.         {
  35.             if(_resourceManagerFactory == null)
  36.             {
  37.                 return Path.Combine(ResoucePath, typeof (T).Name.ToLower() + ".data");
  38.             }
  39.  
  40.             return _resourceManagerFactory.GetFileName();
  41.         }
  42.     }
  43.  
  44.     /// <summary>
  45.     /// Available resources
  46.     /// </summary>
  47.     private static List<T> Resources { get; set; }
  48.  
  49.     /// <summary>
  50.     /// Factory for current resources
  51.     /// </summary>
  52.     private static IResourceManagerFactory<T> _resourceManagerFactory = null;
  53.  
  54.     private static FormatterType _formatterType;
  55.  
  56.     private static UInt16 _currentIdentifireID = 1;
  57.  
  58.     static ResourceManager()
  59.     {
  60.         if (Attribute.GetCustomAttribute(typeof(T), typeof(SerializableAttribute)) == null)
  61.             throw new SystemException("Error creating resource manager: type '" + typeof(T).FullName + "' is not marked as serializable");
  62.  
  63.         Resources = new List<T>();
  64.         IsLoaded = false;
  65.         _formatterType = FormatterType.Binary;
  66.     }
  67.  
  68.     /// <summary>
  69.     /// Registering a serialize and deserialize factory for current resource type
  70.     /// </summary>
  71.     /// <param name="factory"></param>
  72.     public static void RegisterFactory(IResourceManagerFactory<T> factory)
  73.     {
  74.         lock (_lock)
  75.         {
  76.             Logger.Log("Register factory \'" + factory.GetType().Name + "\' for type \'" + typeof(T).Name + "\'");
  77.             _resourceManagerFactory = factory;
  78.         }
  79.        
  80.     }
  81.  
  82.     /// <summary>
  83.     /// Get Resource By It's personal ID
  84.     /// </summary>
  85.     /// <param name="id"></param>
  86.     /// <returns></returns>
  87.     public static T GetResource(int id)
  88.     {
  89.         lock (_lock)
  90.         {
  91.             return Resources.First(e => e.ID == id);
  92.         }
  93.     }
  94.  
  95.     /// <summary>
  96.     /// Adding resources and settint to it its personal ID
  97.     /// </summary>
  98.     /// <param name="item"></param>
  99.     public static void AddResource(T item)
  100.     {
  101.         lock (_lock)
  102.         {
  103.             item.ID = _currentIdentifireID;
  104.  
  105.             _currentIdentifireID++;
  106.  
  107.             Resources.Add(item);
  108.         }
  109.     }
  110.  
  111.     /// <summary>
  112.     /// Getting all resources
  113.     /// </summary>
  114.     /// <returns></returns>
  115.     public static IEnumerable<T> GetResources()
  116.     {
  117.         lock (_lock)
  118.         {
  119.             return Resources;
  120.         }
  121.        
  122.     }
  123.  
  124.     /// <summary>
  125.     /// Setting serialize/deserialize formatter
  126.     /// Custom means using personal factory
  127.     /// </summary>
  128.     /// <param name="type"></param>
  129.     public static void SetFormatterType(FormatterType type)
  130.     {
  131.         _formatterType = type;
  132.     }
  133.  
  134.  
  135.     /// <summary>
  136.     /// Load resources from file (without checking if already loaded into memory)
  137.     /// </summary>
  138.     public static void Load()
  139.     {
  140.         lock (_lock)
  141.         {
  142.             IsLoaded = true;
  143.             Logger.Log("Loading resources of type \'" + typeof(T).Name + "\'... (Formatter type:" + _formatterType.ToString() + ")");
  144.  
  145.             switch (_formatterType)
  146.             {
  147.                 case FormatterType.Binary:
  148.                     if (File.Exists(ResourceFilename))
  149.                     {
  150.                         var formatter = new BinaryFormatter();
  151.  
  152.                         using (var stream = new FileStream(ResourceFilename, FileMode.Open, FileAccess.Read))
  153.                         {
  154.                             try
  155.                             {
  156.                                 Resources = (List<T>)formatter.Deserialize(stream);
  157.  
  158.                                 // Initializing complex resources
  159.                                 foreach (T resource in Resources)
  160.                                 {
  161.                                     resource.Initialize();
  162.                                 }
  163.  
  164.                             }
  165.                             catch (Exception)
  166.                             {
  167.                                 Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
  168.                                 Resources = new List<T>();
  169.                             }
  170.                         }
  171.                     }
  172.                     else
  173.                     {
  174.                         Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "': file not exists!");
  175.                         Resources = new List<T>();
  176.  
  177.                     }
  178.                     break;
  179.                 case FormatterType.JSON:
  180.                     string data = File.ReadAllText(ResourceFilename);
  181.  
  182.                     Resources = JsonConvert.DeserializeObject<List<T>>(data);
  183.                     break;
  184.                 case FormatterType.Custom:
  185.                     if (_resourceManagerFactory != null)
  186.                     {
  187.                         try
  188.                         {
  189.                             Resources = _resourceManagerFactory.Deserialize();
  190.                         }
  191.                         catch (Exception)
  192.                         {
  193.                             Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
  194.                             Resources = new List<T>();
  195.  
  196.                         }
  197.                     }
  198.                     else
  199.                     {
  200.                         Logger.Log("ResourceManager", "Cannot find ResourceFactory for type '" + typeof(T).Name + "'");
  201.                     }
  202.                     break;
  203.                 default:
  204.                     throw new ArgumentOutOfRangeException();
  205.             }
  206.  
  207.             // Initializing complex resources
  208.             foreach (T resource in Resources)
  209.             {
  210.                 resource.Initialize();
  211.             }
  212.  
  213.             if (Resources.Count > 0)
  214.                 _currentIdentifireID = (ushort)(Resources.Max(e => e.ID) + 1);
  215.             else
  216.                 _currentIdentifireID = 1;
  217.  
  218.             Logger.Log("Loading resources of type \'" + typeof(T).Name + "\' done!");
  219.         }
  220.     }
  221.  
  222.     /// <summary>
  223.     /// Load resources from file with specified formatter with cheking if resources already downloaded
  224.     /// </summary>
  225.     /// <param name="formatter"></param>
  226.     public static void Load(FormatterType formatter)
  227.     {
  228.         if (IsLoaded)
  229.             return;
  230.  
  231.         SetFormatterType(formatter);
  232.  
  233.         Load();
  234.     }
  235.  
  236.     /// <summary>
  237.     /// Save resources
  238.     /// </summary>
  239.     public static void Save()
  240.     {
  241.         lock (_lock)
  242.         {
  243.             Logger.Log("Saving resources of type \'" + typeof(T).Name + "\'");
  244.             if (!Directory.Exists(ResoucePath))
  245.                 Directory.CreateDirectory(ResoucePath);
  246.  
  247.  
  248.             switch (_formatterType)
  249.             {
  250.                 case FormatterType.Binary:
  251.                     var formatter = new BinaryFormatter();
  252.  
  253.                     using (var stream = new FileStream(ResourceFilename, FileMode.OpenOrCreate, FileAccess.Write))
  254.                     {
  255.                         try
  256.                         {
  257.                             formatter.Serialize(stream, Resources);
  258.                         }
  259.                         catch (Exception ex)
  260.                         {
  261.                             Logger.Log("ResourceManager", "Cannot save '" + typeof(T).Name + "'.\n Exception: " + ex.Source + ex.Message + "\n" + ex.StackTrace);
  262.                             Resources = new List<T>();
  263.                         }
  264.                     }
  265.                     break;
  266.                 case FormatterType.JSON:
  267.                     string result = JsonConvert.SerializeObject(Resources, Formatting.Indented);
  268.  
  269.                     File.WriteAllText(ResourceFilename, result);
  270.                     break;
  271.                 case FormatterType.Custom:
  272.                     if (_resourceManagerFactory != null)
  273.                     {
  274.                         try
  275.                         {
  276.                             _resourceManagerFactory.Serialize(Resources);
  277.                         }
  278.                         catch (Exception)
  279.                         {
  280.                             Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
  281.                             Resources = new List<T>();
  282.                         }
  283.                     }
  284.                     else
  285.                     {
  286.                         Logger.Log("ResourceManager", "Cannot find ResourceFactory for type '" + typeof(T).Name + "'");
  287.                     }
  288.                     break;
  289.                 default:
  290.                     throw new ArgumentOutOfRangeException();
  291.             }
  292.         }
  293.     }
  294. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement