Click here to Skip to main content
15,896,456 members
Articles / Web Development / ASP.NET

Easier .NET settings

Rate me:
Please Sign up or sign in to vote.
4.91/5 (102 votes)
17 Apr 2014CPOL23 min read 173K   3.3K   311  
Creating a library for persisting the application state data between work sessions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracking.DataStoring;
using Tracking.Serialization;
using System.Windows;
using System.Diagnostics;
using System.Reflection;
using System.Web;

namespace Tracking
{
    public class SettingsTracker
    {
        List<TrackingConfiguration> _configurations = new List<TrackingConfiguration>();

        public string Name { get; set; }

        IObjectStore _objectStore;
        public SettingsTracker(IObjectStore objectStore)
        {
            _objectStore = objectStore;
            WireUpAutomaticPersist();
        }

        #region automatic persisting
        protected virtual void WireUpAutomaticPersist()
        {
            if (System.Windows.Application.Current != null)//wpf
                System.Windows.Application.Current.Exit += (s, e) => { PersistAutomaticTargets(); };
            else //winforms
                System.Windows.Forms.Application.ApplicationExit += (s, e) => { PersistAutomaticTargets(); };
        }

        public void PersistAutomaticTargets()
        {
            foreach (TrackingConfiguration config in _configurations.Where(cfg => cfg.Mode == PersistModes.Automatic && cfg.TargetReference.IsAlive))
                PersistState(config.TargetReference.Target);
        }
        #endregion

        public TrackingConfiguration Configure(object target)
        {
            TrackingConfiguration config = FindExistingConfig(target);
            if (config == null)
            {
                config = new TrackingConfiguration(target) { TrackerName = Name };
                _configurations.Add(config);
            }
            return config;
        }

        public void ApplyAllState()
        {
            foreach (TrackingConfiguration config in _configurations.Where(c=>c.TargetReference.IsAlive))
                ApplyState(config.TargetReference.Target);
        }

        public void ApplyState(object target)
        {
            TrackingConfiguration config = FindExistingConfig(target);
            Debug.Assert(config != null);

            ITrackingAware trackingAwareTarget = target as ITrackingAware;
            if ((trackingAwareTarget == null) || trackingAwareTarget.OnApplyingState(config))
            {
                foreach (string propertyName in config.Properties)
                {
                    PropertyInfo property = target.GetType().GetProperty(propertyName);
                    string propKey = ConstructPropertyKey(target.GetType().FullName, config.Key, property.Name);
                    try
                    {
                        if (_objectStore.ContainsKey(propKey))
                        {
                            object storedValue = _objectStore.Retrieve(propKey);
                            property.SetValue(target, storedValue, null);
                        }
                    }
                    catch
                    {
                        Debug.WriteLine("Applying of value '{propKey}' failed!");
                    }
                }
            }
        }

        public void PersistState(object target)
        {
            TrackingConfiguration config = FindExistingConfig(target);
            Debug.Assert(config != null);

            ITrackingAware trackingAwareTarget = target as ITrackingAware;
            if ((trackingAwareTarget == null) || trackingAwareTarget.OnPersistingState(config))
            {
                foreach (string propertyName in config.Properties)
                {
                    PropertyInfo property = target.GetType().GetProperty(propertyName);

                    string propKey = ConstructPropertyKey(target.GetType().FullName, config.Key, property.Name);
                    try
                    {
                        object currentValue = property.GetValue(target, null);
                        _objectStore.Persist(currentValue, propKey);
                    }
                    catch 
                    {
                        Debug.WriteLine("Persisting of value '{propKey}' failed!");
                    }
                }
            }
        }

        #region private helper methods
        
        private TrackingConfiguration FindExistingConfig(object target)
        {
            //.TargetReference.Target ---> (TrackedTarget).(WeakReferenceTarget)
            return _configurations.SingleOrDefault(cfg => cfg.TargetReference.Target == target);
        }

        //helper method for creating an identifier from the object type, object key, and the propery name
        private string ConstructPropertyKey(string targetTypeName, string objectKey, string propertyName)
        {
            return string.Format("{0}_{1}.{2}", targetTypeName, objectKey, propertyName);
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Recro-Net
Croatia Croatia
I have been an a(tra)ctive software developer since 2005 mostly working on .NET. Currently living and working in Zagreb Croatia. I have earned my masters degree in Computer Science at the Faculty of Electrical Engineering and Computer Science in Zagreb in 2006.

Comments and Discussions