Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Type of serialization
- /// Custom means registered ResourceFactory
- /// </summary>
- public enum FormatterType
- {
- Binary, JSON, Custom
- }
- /// <summary>
- /// Thread safe Resource Manager for UniqueEntity-based types
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public static class ResourceManager<T> where T : UniqueEntity
- {
- /// <summary>
- /// Default resource directory. (Value: "data")
- /// </summary>
- public static string ResoucePath = "data";
- private static object _lock = new object();
- /// <summary>
- /// Determines if resources were load or not
- /// </summary>
- public static bool IsLoaded { get; private set; }
- /// <summary>
- /// Gets the path and filename for resource
- /// </summary>
- public static string ResourceFilename
- {
- get
- {
- if(_resourceManagerFactory == null)
- {
- return Path.Combine(ResoucePath, typeof (T).Name.ToLower() + ".data");
- }
- return _resourceManagerFactory.GetFileName();
- }
- }
- /// <summary>
- /// Available resources
- /// </summary>
- private static List<T> Resources { get; set; }
- /// <summary>
- /// Factory for current resources
- /// </summary>
- private static IResourceManagerFactory<T> _resourceManagerFactory = null;
- private static FormatterType _formatterType;
- private static UInt16 _currentIdentifireID = 1;
- static ResourceManager()
- {
- if (Attribute.GetCustomAttribute(typeof(T), typeof(SerializableAttribute)) == null)
- throw new SystemException("Error creating resource manager: type '" + typeof(T).FullName + "' is not marked as serializable");
- Resources = new List<T>();
- IsLoaded = false;
- _formatterType = FormatterType.Binary;
- }
- /// <summary>
- /// Registering a serialize and deserialize factory for current resource type
- /// </summary>
- /// <param name="factory"></param>
- public static void RegisterFactory(IResourceManagerFactory<T> factory)
- {
- lock (_lock)
- {
- Logger.Log("Register factory \'" + factory.GetType().Name + "\' for type \'" + typeof(T).Name + "\'");
- _resourceManagerFactory = factory;
- }
- }
- /// <summary>
- /// Get Resource By It's personal ID
- /// </summary>
- /// <param name="id"></param>
- /// <returns></returns>
- public static T GetResource(int id)
- {
- lock (_lock)
- {
- return Resources.First(e => e.ID == id);
- }
- }
- /// <summary>
- /// Adding resources and settint to it its personal ID
- /// </summary>
- /// <param name="item"></param>
- public static void AddResource(T item)
- {
- lock (_lock)
- {
- item.ID = _currentIdentifireID;
- _currentIdentifireID++;
- Resources.Add(item);
- }
- }
- /// <summary>
- /// Getting all resources
- /// </summary>
- /// <returns></returns>
- public static IEnumerable<T> GetResources()
- {
- lock (_lock)
- {
- return Resources;
- }
- }
- /// <summary>
- /// Setting serialize/deserialize formatter
- /// Custom means using personal factory
- /// </summary>
- /// <param name="type"></param>
- public static void SetFormatterType(FormatterType type)
- {
- _formatterType = type;
- }
- /// <summary>
- /// Load resources from file (without checking if already loaded into memory)
- /// </summary>
- public static void Load()
- {
- lock (_lock)
- {
- IsLoaded = true;
- Logger.Log("Loading resources of type \'" + typeof(T).Name + "\'... (Formatter type:" + _formatterType.ToString() + ")");
- switch (_formatterType)
- {
- case FormatterType.Binary:
- if (File.Exists(ResourceFilename))
- {
- var formatter = new BinaryFormatter();
- using (var stream = new FileStream(ResourceFilename, FileMode.Open, FileAccess.Read))
- {
- try
- {
- Resources = (List<T>)formatter.Deserialize(stream);
- // Initializing complex resources
- foreach (T resource in Resources)
- {
- resource.Initialize();
- }
- }
- catch (Exception)
- {
- Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
- Resources = new List<T>();
- }
- }
- }
- else
- {
- Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "': file not exists!");
- Resources = new List<T>();
- }
- break;
- case FormatterType.JSON:
- string data = File.ReadAllText(ResourceFilename);
- Resources = JsonConvert.DeserializeObject<List<T>>(data);
- break;
- case FormatterType.Custom:
- if (_resourceManagerFactory != null)
- {
- try
- {
- Resources = _resourceManagerFactory.Deserialize();
- }
- catch (Exception)
- {
- Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
- Resources = new List<T>();
- }
- }
- else
- {
- Logger.Log("ResourceManager", "Cannot find ResourceFactory for type '" + typeof(T).Name + "'");
- }
- break;
- default:
- throw new ArgumentOutOfRangeException();
- }
- // Initializing complex resources
- foreach (T resource in Resources)
- {
- resource.Initialize();
- }
- if (Resources.Count > 0)
- _currentIdentifireID = (ushort)(Resources.Max(e => e.ID) + 1);
- else
- _currentIdentifireID = 1;
- Logger.Log("Loading resources of type \'" + typeof(T).Name + "\' done!");
- }
- }
- /// <summary>
- /// Load resources from file with specified formatter with cheking if resources already downloaded
- /// </summary>
- /// <param name="formatter"></param>
- public static void Load(FormatterType formatter)
- {
- if (IsLoaded)
- return;
- SetFormatterType(formatter);
- Load();
- }
- /// <summary>
- /// Save resources
- /// </summary>
- public static void Save()
- {
- lock (_lock)
- {
- Logger.Log("Saving resources of type \'" + typeof(T).Name + "\'");
- if (!Directory.Exists(ResoucePath))
- Directory.CreateDirectory(ResoucePath);
- switch (_formatterType)
- {
- case FormatterType.Binary:
- var formatter = new BinaryFormatter();
- using (var stream = new FileStream(ResourceFilename, FileMode.OpenOrCreate, FileAccess.Write))
- {
- try
- {
- formatter.Serialize(stream, Resources);
- }
- catch (Exception ex)
- {
- Logger.Log("ResourceManager", "Cannot save '" + typeof(T).Name + "'.\n Exception: " + ex.Source + ex.Message + "\n" + ex.StackTrace);
- Resources = new List<T>();
- }
- }
- break;
- case FormatterType.JSON:
- string result = JsonConvert.SerializeObject(Resources, Formatting.Indented);
- File.WriteAllText(ResourceFilename, result);
- break;
- case FormatterType.Custom:
- if (_resourceManagerFactory != null)
- {
- try
- {
- _resourceManagerFactory.Serialize(Resources);
- }
- catch (Exception)
- {
- Logger.Log("ResourceManager", "Cannot load resouce of type '" + typeof(T).Name + "'");
- Resources = new List<T>();
- }
- }
- else
- {
- Logger.Log("ResourceManager", "Cannot find ResourceFactory for type '" + typeof(T).Name + "'");
- }
- break;
- default:
- throw new ArgumentOutOfRangeException();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement