Fixed formatting on ProfilesManager.cs

Fixed formatting on ProfilesManager.cs

--- Project-Aurora/Project-Aurora/Profiles/ProfilesManager.cs
+++ Project-Aurora/Project-Aurora/Profiles/ProfilesManager.cs
@@ -1,1282 +1,643 @@
 using Aurora.Profiles.Aurora_Wrapper;
-
 using Aurora.Profiles.Desktop;
-
 using Aurora.Profiles.Generic_Application;
-
 using Aurora.Profiles.Overlays.SkypeOverlay;
-
 using Aurora.Settings;
-
 using Aurora.Settings.Layers;
-
 using Aurora.Utils;
-
 using Newtonsoft.Json;
-
 using Newtonsoft.Json.Linq;
-
 using System;
-
 using System.Collections.Generic;
-
 using System.Diagnostics;
-
 using System.IO;
-
 using System.Linq;
-
 using System.Runtime.InteropServices;
-
 using System.Text;
-
 using System.Threading;
-
-using System.Threading.Tasks;
-
-
-
-namespace Aurora.Profiles
-
-{
-
-    public class ProfilesManager : IInit
-
-    {
-
-        //private static ProfilesManager instance;
-
-
-
-        //public static ProfilesManager Instance { get { return instance ?? (instance = new ProfilesManager()); } }
-
-
-
-        public class LayerHandlerEntry
-
-        {
-
-            public Type Type { get; set; }
-
-
-
-            public string Title { get; set; }
-
-
-
-            public string Key { get; set; }
-
-
-
-            public LayerHandlerEntry(string key, string title, Type type)
-
+using System.Threading.Tasks;
+
+namespace Aurora.Profiles
+{
+    public class ProfilesManager : IInit
+    {
+        //private static ProfilesManager instance;
+
+        //public static ProfilesManager Instance { get { return instance ?? (instance = new ProfilesManager()); } }
+
+        public class LayerHandlerEntry
+        {
+            public Type Type { get; set; }
+
+            public string Title { get; set; }
+
+            public string Key { get; set; }
+
+            public LayerHandlerEntry(string key, string title, Type type)
+            {
+                this.Type = type;
+                this.Title = title;
+                this.Key = key;
+            }
+
+            public override string ToString()
+            {
+                return Title;
+            }
+        }
+
+        /*public class ProfilesManagerSettings
+        {
+            public List<string> ProfileOrder { get; protected set; } = new List<string>();
+        }*/
+
+        public Dictionary<string, ILightEvent> Events { get; private set; } = new Dictionary<string, ILightEvent> { { "desktop", new Desktop.DesktopProfileManager() } };
+
+        public Desktop.DesktopProfileManager DesktopProfile { get { return (Desktop.DesktopProfileManager)Events["desktop"]; } }
+
+        private List<string> Underlays = new List<string>();
+        private List<string> Normal = new List<string>();
+        private List<string> Overlays = new List<string>();
+
+        private Dictionary<string, string> EventProcesses { get; set; } = new Dictionary<string, string>();
+
+        private Dictionary<string, string> EventAppIDs { get; set; } = new Dictionary<string, string>();
+
+        public Dictionary<string, LayerHandlerEntry> LayerHandlers { get; private set; } = new Dictionary<string, LayerHandlerEntry>();
+
+        public List<string> DefaultLayerHandlers { get; private set; } = new List<string>();
+
+        public string AdditionalProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Aurora", "AdditionalProfiles");
+
+        //public string ProfilesManagerSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Aurora", "ProfilesSettings.json");
+
+        //public static ProfilesManagerSettings Settings { get; private set; }
+
+        private ActiveProcessMonitor processMonitor;
+
+        public bool Initialized { get; private set; }
+
+        public bool Initialize()
+        {
+            if (Initialized)
+                return true;
+
+            processMonitor = new ActiveProcessMonitor();
+
+            #region Initiate Defaults
+            RegisterEvents(new List<ILightEvent> {
+                new Desktop.DesktopProfileManager(),
+                new Dota_2.Dota2ProfileManager(),
+                new CSGO.CSGOProfileManager(),
+                new GTA5.GTA5ProfileManager(),
+                new RocketLeague.RocketLeagueProfileManager(),
+                new Overwatch.OverwatchProfileManager(),
+                new Payday_2.PD2ProfileManager(),
+                new TheDivision.TheDivisionProfileManager(),
+                new LeagueOfLegends.LoLProfileManager(),
+                new HotlineMiami.HMProfileManager(),
+                new TheTalosPrinciple.TalosPrincipleProfileManager(),
+                new BF3.BF3ProfileManager(),
+                new Blacklight.BLightProfileManager(),
+                new Magic_Duels_2012.MagicDuels2012ProfileManager(),
+                new ShadowOfMordor.ShadowOfMordorProfileManager(),
+                new Serious_Sam_3.SSam3ProfileManager(),
+                new DiscoDodgeball.DiscoDodgeballProfileManager(),
+                new XCOM.XCOMProfileManager(),
+                new Evolve.EvolveProfileManager(),
+                new Metro_Last_Light.MetroLLProfileManager(),
+                new Guild_Wars_2.GW2ProfileManager(),
+                new WormsWMD.WormsWMDProfileManager(),
+                new Blade_and_Soul.BnSProfileManager(),
+                new Event_SkypeOverlay()
+            });
+
+            RegisterLayerHandlers(new List<LayerHandlerEntry> {
+                new LayerHandlerEntry("Default", "Default Layer", typeof(DefaultLayerHandler)),
+                new LayerHandlerEntry("Solid", "Solid Color Layer", typeof(SolidColorLayerHandler)),
+                new LayerHandlerEntry("SolidFilled", "Solid Fill Color Layer", typeof(SolidFillLayerHandler)),
+                new LayerHandlerEntry("Gradient", "Gradient Layer", typeof(GradientLayerHandler)),
+                new LayerHandlerEntry("GradientFill", "Gradient Fill Layer", typeof(GradientFillLayerHandler)),
+                new LayerHandlerEntry("Breathing", "Breathing Layer", typeof(BreathingLayerHandler)),
+                new LayerHandlerEntry("Blinking", "Blinking Layer", typeof(BlinkingLayerHandler)),
+                new LayerHandlerEntry("Image", "Image Layer", typeof(ImageLayerHandler)),
+                new LayerHandlerEntry("Script", "Script Layer", typeof(ScriptLayerHandler)),
+                new LayerHandlerEntry("Percent", "Percent Effect Layer", typeof(PercentLayerHandler)),
+                new LayerHandlerEntry("PercentGradient", "Percent (Gradient) Effect Layer", typeof(PercentGradientLayerHandler)),
+                new LayerHandlerEntry("Interactive", "Interactive Layer", typeof(InteractiveLayerHandler) ),
+                new LayerHandlerEntry("ShortcutAssistant", "Shortcut Assistant Layer", typeof(ShortcutAssistantLayerHandler) ),
+                new LayerHandlerEntry("Equalizer", "Equalizer Layer", typeof(EqualizerLayerHandler) ),
+                new LayerHandlerEntry("Ambilight", "Ambilight Layer", typeof(AmbilightLayerHandler) ),
+                new LayerHandlerEntry("LockColor", "Lock Color Layer", typeof(LockColourLayerHandler) ),
+                new LayerHandlerEntry("Glitch", "Glitch Effect Layer", typeof(GlitchLayerHandler) ),
+                new LayerHandlerEntry("Animation", "Animation Layer", typeof(AnimationLayerHandler) ),
+            }, true);
+
+            #endregion
+
+            if (Directory.Exists(AdditionalProfilesPath))
+            {
+                List<string> additionals = new List<string>(Directory.EnumerateDirectories(AdditionalProfilesPath));
+                foreach (var dir in additionals)
+                {
+                    if (File.Exists(Path.Combine(dir, "default.json")))
+                    {
+                        string proccess_name = Path.GetFileName(dir);
+                        RegisterEvent(new GenericApplicationProfileManager(proccess_name));
+                    }
+                }
+            }
+
+            foreach (var profile in Events)
+            {
+                profile.Value.Initialize();
+            }
+
+            LoadSettings();
+
+            this.InitUpdate();
+
+            Initialized = true;
+            return Initialized;
+        }
+
+        private void LoadSettings()
+        {
+            /*if (File.Exists(ProfilesManagerSettingsPath))
+            {
+                try
+                {
+                    Settings = JsonConvert.DeserializeObject<ProfilesManagerSettings>(File.ReadAllText(ProfilesManagerSettingsPath), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
+                }
+                catch (Exception exc)
+                {
+                    Global.logger.LogLine("Exception occured while loading Profiles Settings.\nException:" + exc, Logging_Level.Error);
+                    SaveSettings();
+                }
+            }
+            else
+                SaveSettings();*/
+
+            foreach (var kvp in Events)
+            {
+                if (!Global.Configuration.ProfileOrder.Contains(kvp.Key) && kvp.Value is ProfileManager)
+                    Global.Configuration.ProfileOrder.Add(kvp.Key);
+            }
+
+            foreach (string key in Global.Configuration.ProfileOrder.ToList())
+            {
+                if (!Events.ContainsKey(key) || !(Events[key] is ProfileManager))
+                    Global.Configuration.ProfileOrder.Remove(key);
+            }
+
+            Global.Configuration.ProfileOrder.Remove("desktop");
+            Global.Configuration.ProfileOrder.Insert(0, "desktop");
+        }
+
+        /*public static void SaveSettings()
+        {
+            if (Settings == null)
+                Settings = new ProfilesManagerSettings();
+
+            File.WriteAllText(ProfilesManagerSettingsPath, JsonConvert.SerializeObject(Settings, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }));
+        }*/
+
+        public void SaveAll()
+        {
+            //SaveSettings();
+
+            foreach (var profile in Events)
+            {
+                if (profile.Value is ProfileManager)
+                    ((ProfileManager)profile.Value).SaveProfiles();
+            }
+        }
+
+        public bool RegisterProfile(LightEventConfig config)
+        {
+            return RegisterEvent(new ProfileManager(config));
+        }
+
+        private List<string> GetEventTable(LightEventType type)
+        {
+            List<string> events;
+            switch (type)
+            {
+                case LightEventType.Normal:
+                    events = Normal;
+                    break;
+                case LightEventType.Overlay:
+                    events = Overlays;
+                    break;
+                case LightEventType.Underlay:
+                    events = Underlays;
+                    break;
+                default:
+                    throw new NotImplementedException();
+            }
+            return events;
+        }
+
+        private bool InsertLightEvent(ILightEvent lightEvent, LightEventType? old = null)
+        {
+            if (old == null)
+            {
+                lightEvent.Config.PropertyChanged += LightEvent_PropertyChanged;
+            }
+            else
+            {
+                var oldEvents = GetEventTable((LightEventType)old);
+                oldEvents.Remove(lightEvent.Config.ID);
+            }
+
+            var events = GetEventTable(lightEvent.Config.Type);
+
+            events.Add(lightEvent.Config.ID);
+
+            return true;
+
+        }
+
+        private void LightEvent_PropertyChanged(object sender, PropertyChangedExEventArgs e)
+        {
+            ILightEvent lightEvent = (ILightEvent)sender;
+            if (e.PropertyName.Equals(nameof(LightEventConfig.Type)))
+            {
+                LightEventType old = (LightEventType)e.OldValue;
+                LightEventType newVal = (LightEventType)e.NewValue;
+
+                if (!old.Equals(newVal))
+                {
+                    InsertLightEvent(lightEvent, old);
+                }
+            }
+        }
+
+        public bool RegisterEvent(ILightEvent @event)
+        {
+            string key = @event.Config.ID;
+            if (string.IsNullOrWhiteSpace(key) || Events.ContainsKey(key))
+                return false;
+
+            Events.Add(key, @event);
+
+            if (@event.Config.ProcessNames != null)
+            {
+                foreach (string exe in @event.Config.ProcessNames)
+                {
+                    if (!exe.Equals(key))
+                        EventProcesses.Add(exe, key);
+                }
+            }
+
+            if (!String.IsNullOrWhiteSpace(@event.Config.AppID))
+                EventAppIDs.Add(@event.Config.AppID, key);
+
+            if (@event is ProfileManager)
+            {
+                if (!Global.Configuration.ProfileOrder.Contains(key))
+                    Global.Configuration.ProfileOrder.Add(key);
+            }
+
+            this.InsertLightEvent(@event);
+
+            if (Initialized)
+                @event.Initialize();
+
+            return true;
+        }
+
+        public void RegisterProfiles(List<LightEventConfig> profiles)
+        {
+            foreach (var profile in profiles)
+            {
+                RegisterProfile(profile);
+            }
+        }
+
+        public void RegisterEvents(List<ILightEvent> profiles)
+        {
+            foreach (var profile in profiles)
+            {
+                RegisterEvent(profile);
+            }
+        }
+
+        public void RemoveGenericProfile(string key)
+        {
+            if (Events.ContainsKey(key))
+            {
+                if (!(Events[key] is GenericApplicationProfileManager))
+                    return;
+                GenericApplicationProfileManager profile = (GenericApplicationProfileManager)Events[key];
+                string path = profile.GetProfileFolderPath();
+                if (Directory.Exists(path))
+                    Directory.Delete(path, true);
+
+                Events.Remove(key);
+                Global.Configuration.ProfileOrder.Remove(key);
+
+                //SaveSettings();
+            }
+        }
+
+        public ILightEvent GetProfileFromProcess(string process)
+        {
+            if (EventProcesses.ContainsKey(process))
+                return Events[EventProcesses[process]];
+            else if (Events.ContainsKey(process))
+                return Events[process];
+            else if (Events.ContainsKey(process))
+                return Events[process];
+
+
+            return null;
+        }
+
+        public ILightEvent GetProfileFromAppID(string appid)
+        {
+            if (EventAppIDs.ContainsKey(appid))
+                return Events[EventAppIDs[appid]];
+            else if (Events.ContainsKey(appid))
+                return Events[appid];
+            else if (Events.ContainsKey(appid))
+                return Events[appid];
+
+            return null;
+        }
+
+        public void RegisterLayerHandlers(List<LayerHandlerEntry> layers, bool @default = true)
+        {
+            foreach (var layer in layers)
+            {
+                RegisterLayerHandler(layer, @default);
+            }
+        }
+
+        public bool RegisterLayerHandler(LayerHandlerEntry entry, bool @default = true)
+        {
+            if (LayerHandlers.ContainsKey(entry.Key) || DefaultLayerHandlers.Contains(entry.Key))
+                return false;
+
+            LayerHandlers.Add(entry.Key, entry);
+
+            if (@default)
+                DefaultLayerHandlers.Add(entry.Key);
+
+            return true;
+        }
+
+        public bool RegisterLayerHandler(string key, string title, Type type, bool @default = true)
+        {
+            return RegisterLayerHandler(new LayerHandlerEntry(key, title, type));
+        }
+
+        public Type GetLayerHandlerType(string key)
+        {
+            return LayerHandlers.ContainsKey(key) ? LayerHandlers[key].Type : null;
+        }
+
+        public ILayerHandler GetLayerHandlerInstance(LayerHandlerEntry entry)
+        {
+            return (ILayerHandler)Activator.CreateInstance(entry.Type);
+        }
+
+        public ILayerHandler GetLayerHandlerInstance(string key)
+        {
+            if (LayerHandlers.ContainsKey(key))
+            {
+                return GetLayerHandlerInstance(LayerHandlers[key]);
+            }
+
+
+            return null;
+        }
+
+        private Timer updateTimer;
+
+        private const int defaultTimerInterval = 33;
+        private int timerInterval = defaultTimerInterval;
+
+        private long nextProcessNameUpdate;
+        private long currentTick;
+        private string previewModeProfileKey = "";
+
+        private List<TimedListObject> overlays = new List<TimedListObject>();
+        private Event_Idle idle_e = new Event_Idle();
+
+        public string PreviewProfileKey { get { return previewModeProfileKey; } set { previewModeProfileKey = value ?? string.Empty; } }
+
+        private void InitUpdate()
+        {
+            updateTimer = new System.Threading.Timer(g =>
+            {
+                Stopwatch watch = new Stopwatch();
+                watch.Start();
+                try
+                {
+                    Update();
+                }
+                catch (Exception exc)
+                {
+                    Global.logger.LogLine("ProfilesManager.Update() Exception, " + exc, Logging_Level.Error);
+                }
+
+                watch.Stop();
+                currentTick += timerInterval + watch.ElapsedMilliseconds;
+                updateTimer?.Change(Math.Max(timerInterval, 0), Timeout.Infinite);
+            }, null, 0, System.Threading.Timeout.Infinite);
+            GC.KeepAlive(updateTimer);
+        }
+
+        private void UpdateProcess()
+        {
+            if (Global.Configuration.detection_mode == Settings.ApplicationDetectionMode.ForegroroundApp && (currentTick >= nextProcessNameUpdate))
+            {
+                processMonitor.GetActiveWindowsProcessname();
+                nextProcessNameUpdate = currentTick + 1000L;
+            }
+        }
+
+        private void UpdateIdleEffects(EffectsEngine.EffectFrame newFrame)
+        {
+            tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
+            Int32 IdleTime;
+            LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
+            LastInput.dwTime = 0;
+
+            if (ActiveProcessMonitor.GetLastInputInfo(ref LastInput))
+            {
+                IdleTime = System.Environment.TickCount - LastInput.dwTime;
+
+                if (IdleTime >= Global.Configuration.idle_delay * 60 * 1000)
+                {
+                    if (!(Global.Configuration.time_based_dimming_enabled &&
+                    Utils.Time.IsCurrentTimeBetween(Global.Configuration.time_based_dimming_start_hour, Global.Configuration.time_based_dimming_start_minute, Global.Configuration.time_based_dimming_end_hour, Global.Configuration.time_based_dimming_end_minute))
+                    )
+                    {
+                        idle_e.UpdateLights(newFrame);
+                    }
+                }
+            }
+        }
+
+        private void Update()
+        {
+            //Blackout. TODO: Cleanup this a bit. Maybe push blank effect frame to keyboard incase it has existing stuff displayed
+            if ((Global.Configuration.time_based_dimming_enabled &&
+               Utils.Time.IsCurrentTimeBetween(Global.Configuration.time_based_dimming_start_hour, Global.Configuration.time_based_dimming_start_minute, Global.Configuration.time_based_dimming_end_hour, Global.Configuration.time_based_dimming_end_minute)))
+                return;
+
+            UpdateProcess();
+
+            string process_name = System.IO.Path.GetFileName(processMonitor.ProcessPath).ToLowerInvariant();
+
+            EffectsEngine.EffectFrame newFrame = new EffectsEngine.EffectFrame();
+
+            foreach (var underlay in Underlays)
+            {
+                ILightEvent @event = Events[underlay];
+                if (@event.IsEnabled && (@event.Config.ProcessNames == null || ProcessUtils.AnyProcessExists(@event.Config.ProcessNames)))
+                    @event.UpdateLights(newFrame);
+            }
+
+            //TODO: Move these IdleEffects to an event
+            //this.UpdateIdleEffects(newFrame);
+
+            ILightEvent profile = null;
+            ILightEvent tempProfile = null;
+            //Global.logger.LogLine(process_name);
+            if (!Global.Configuration.excluded_programs.Contains(process_name))
+            {
+
+                //TODO: GetProfile that checks based on event type
+
+                if ((((tempProfile = GetProfileFromProcess(process_name)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
+                    || (((tempProfile = GetProfileFromProcess(previewModeProfileKey)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
+                    || (Global.Configuration.allow_wrappers_in_background && Global.net_listener != null && Global.net_listener.IsWrapperConnected && ((tempProfile = GetProfileFromProcess(Global.net_listener.WrappedProcess)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
+                )
+                    profile = tempProfile;
+            }
+
+            profile = profile ?? DesktopProfile;
+
+            timerInterval = (profile as ProfileManager)?.Config?.UpdateInterval ?? defaultTimerInterval;
+
+            //Check if any keybinds have been triggered
+            foreach (var prof in (profile as ProfileManager).Profiles)
+            {
+                if (prof.TriggerKeybind.IsPressed() && !(profile as ProfileManager).Settings.ProfileName.Equals(prof.ProfileName))
+                {
+                    (profile as ProfileManager).SwitchToProfile(prof);
+                    break;
+                }
+            }
+
+            Global.dev_manager.InitializeOnce();
+            profile.UpdateLights(newFrame);
+
+            foreach (var overlay in Overlays)
+            {
+                ILightEvent @event = Events[overlay];
+                if (@event.IsEnabled && (@event.Config.ProcessNames == null || ProcessUtils.AnyProcessExists(@event.Config.ProcessNames)))
+                    @event.UpdateLights(newFrame);
+            }
+
+            //Add overlays
+            TimedListObject[] overlay_events = overlays.ToArray();
+            foreach (TimedListObject evnt in overlay_events)
+            {
+                if ((evnt.item as LightEvent).IsEnabled)
+                    (evnt.item as LightEvent).UpdateLights(newFrame);
+            }
+
+            Global.effengine.PushFrame(newFrame);
+        }
+
+        public void GameStateUpdate(IGameState gs)
+        {
+            //Debug.WriteLine("Received gs!");
+
+            //Global.logger.LogLine(gs.ToString(), Logging_Level.None, false);
+
+            //UpdateProcess();
+
+            string process_name = System.IO.Path.GetFileName(processMonitor.ProcessPath).ToLowerInvariant();
+
+            //EffectsEngine.EffectFrame newFrame = new EffectsEngine.EffectFrame();
+
+            try
             {
-
-                this.Type = type;
-
-                this.Title = title;
-
-                this.Key = key;
-
+                ILightEvent profile = this.GetProfileFromProcess(process_name);
+
+                JObject provider = Newtonsoft.Json.Linq.JObject.Parse(gs.GetNode("provider"));
+                string appid = provider.GetValue("appid").ToString();
+                string name = provider.GetValue("name").ToString().ToLowerInvariant();
+
+                if ((profile != null || (profile = GetProfileFromAppID(appid)) != null || (profile = GetProfileFromProcess(name)) != null) && (profile.Config != null && profile.Config.GameStateType != null))
+                    profile.SetGameState((IGameState)Activator.CreateInstance(profile.Config.GameStateType, gs));
+                else if (gs is GameState_Wrapper && Global.Configuration.allow_all_logitech_bitmaps)
+                {
+                    string gs_process_name = Newtonsoft.Json.Linq.JObject.Parse(gs.GetNode("provider")).GetValue("name").ToString().ToLowerInvariant();
+                    profile = profile ?? GetProfileFromProcess(gs_process_name);
+                    if (profile == null)
+                    {
+                        Events.Add(gs_process_name, new GameEvent_Aurora_Wrapper());
+                        profile = Events[gs_process_name];
+                    }
+
+                    profile.SetGameState(gs);
+                }
+                //UpdateIdleEffects(newFrame);
             }
-
-
-
-            public override string ToString()
-
+            catch (Exception e)
             {
-
-                return Title;
-
+                Global.logger.LogLine("Exception during GameStateUpdate(), error: " + e, Logging_Level.Warning);
             }
-
-        }
-
-
-
-        /*public class ProfilesManagerSettings
-
-        {
-
-            public List<string> ProfileOrder { get; protected set; } = new List<string>();
-
-        }*/
-
-
-
-        public Dictionary<string, ILightEvent> Events { get; private set; } = new Dictionary<string, ILightEvent> { { "desktop", new Desktop.DesktopProfileManager() } };
-
-
-
-        public Desktop.DesktopProfileManager DesktopProfile { get { return (Desktop.DesktopProfileManager)Events["desktop"]; } }
-
-
-
-        private List<string> Underlays = new List<string>();
-
-        private List<string> Normal = new List<string>();
-
-        private List<string> Overlays = new List<string>();
-
-
-
-        private Dictionary<string, string> EventProcesses { get; set; } = new Dictionary<string, string>();
-
-
-
-        private Dictionary<string, string> EventAppIDs { get; set; } = new Dictionary<string, string>();
-
-
-
-        public Dictionary<string, LayerHandlerEntry> LayerHandlers { get; private set; } = new Dictionary<string, LayerHandlerEntry>();
-
-
-
-        public List<string> DefaultLayerHandlers { get; private set; } = new List<string>();
-
-
-
-        public string AdditionalProfilesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Aurora", "AdditionalProfiles");
-
-
-
-        //public string ProfilesManagerSettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Aurora", "ProfilesSettings.json");
-
-
-
-        //public static ProfilesManagerSettings Settings { get; private set; }
-
-
-
-        private ActiveProcessMonitor processMonitor;
-
-
-
-        public bool Initialized { get; private set; }
-
-
-
-        public bool Initialize()
-
-        {
-
-            if (Initialized)
-
-                return true;
-
-
-
-            processMonitor = new ActiveProcessMonitor();
-
-
-
-            #region Initiate Defaults
-
-            RegisterEvents(new List<ILightEvent> {
-
-                new Desktop.DesktopProfileManager(),
-
-                new Dota_2.Dota2ProfileManager(),
-
-                new CSGO.CSGOProfileManager(),
-
-                new GTA5.GTA5ProfileManager(),
-
-                new RocketLeague.RocketLeagueProfileManager(),
-
-                new Overwatch.OverwatchProfileManager(),
-
-                new Payday_2.PD2ProfileManager(),
-
-                new TheDivision.TheDivisionProfileManager(),
-
-                new LeagueOfLegends.LoLProfileManager(),
-
-                new HotlineMiami.HMProfileManager(),
-
-                new TheTalosPrinciple.TalosPrincipleProfileManager(),
-
-                new BF3.BF3ProfileManager(),
-
-                new Blacklight.BLightProfileManager(),
-
-                new Magic_Duels_2012.MagicDuels2012ProfileManager(),
-
-                new ShadowOfMordor.ShadowOfMordorProfileManager(),
-
-                new Serious_Sam_3.SSam3ProfileManager(),
-
-                new DiscoDodgeball.DiscoDodgeballProfileManager(),
-
-                new XCOM.XCOMProfileManager(),
-
-                new Evolve.EvolveProfileManager(),
-
-                new Metro_Last_Light.MetroLLProfileManager(),
-
-                new Guild_Wars_2.GW2ProfileManager(),
-
-                new WormsWMD.WormsWMDProfileManager(),
-
-                new Blade_and_Soul.BnSProfileManager(),
-
-                new Event_SkypeOverlay()
-
-            });
-
-
-
-            RegisterLayerHandlers(new List<LayerHandlerEntry> {
-
-                new LayerHandlerEntry("Default", "Default Layer", typeof(DefaultLayerHandler)),
-
-                new LayerHandlerEntry("Solid", "Solid Color Layer", typeof(SolidColorLayerHandler)),
-
-                new LayerHandlerEntry("SolidFilled", "Solid Fill Color Layer", typeof(SolidFillLayerHandler)),
-
-                new LayerHandlerEntry("Gradient", "Gradient Layer", typeof(GradientLayerHandler)),
-
-                new LayerHandlerEntry("GradientFill", "Gradient Fill Layer", typeof(GradientFillLayerHandler)),
-
-                new LayerHandlerEntry("Breathing", "Breathing Layer", typeof(BreathingLayerHandler)),
-
-                new LayerHandlerEntry("Blinking", "Blinking Layer", typeof(BlinkingLayerHandler)),
-
-                new LayerHandlerEntry("Image", "Image Layer", typeof(ImageLayerHandler)),
-
-                new LayerHandlerEntry("Script", "Script Layer", typeof(ScriptLayerHandler)),
-
-                new LayerHandlerEntry("Percent", "Percent Effect Layer", typeof(PercentLayerHandler)),
-
-                new LayerHandlerEntry("PercentGradient", "Percent (Gradient) Effect Layer", typeof(PercentGradientLayerHandler)),
-
-                new LayerHandlerEntry("Interactive", "Interactive Layer", typeof(InteractiveLayerHandler) ),
-
-                new LayerHandlerEntry("ShortcutAssistant", "Shortcut Assistant Layer", typeof(ShortcutAssistantLayerHandler) ),
-
-                new LayerHandlerEntry("Equalizer", "Equalizer Layer", typeof(EqualizerLayerHandler) ),
-
-                new LayerHandlerEntry("Ambilight", "Ambilight Layer", typeof(AmbilightLayerHandler) ),
-
-                new LayerHandlerEntry("LockColor", "Lock Color Layer", typeof(LockColourLayerHandler) ),
-
-                new LayerHandlerEntry("Glitch", "Glitch Effect Layer", typeof(GlitchLayerHandler) ),
-
-                new LayerHandlerEntry("Animation", "Animation Layer", typeof(AnimationLayerHandler) ),
-
-            }, true);
-
-
-
-            #endregion
-
-
-
-            if (Directory.Exists(AdditionalProfilesPath))
-
-            {
-
-                List<string> additionals = new List<string>(Directory.EnumerateDirectories(AdditionalProfilesPath));
-
-                foreach (var dir in additionals)
-
-                {
-
-                    if (File.Exists(Path.Combine(dir, "default.json")))
-
-                    {
-
-                        string proccess_name = Path.GetFileName(dir);
-
-                        RegisterEvent(new GenericApplicationProfileManager(proccess_name));
-
-                    }
-
-                }
-
-            }
-
-
-
-            foreach (var profile in Events)
-
-            {
-
-                profile.Value.Initialize();
-
-            }
-
-
-
-            LoadSettings();
-
-
-
-            this.InitUpdate();
-
-
-
-            Initialized = true;
-
-            return Initialized;
-
-        }
-
-
-
-        private void LoadSettings()
-
-        {
-
-            /*if (File.Exists(ProfilesManagerSettingsPath))
-
-            {
-
-                try
-
-                {
-
-                    Settings = JsonConvert.DeserializeObject<ProfilesManagerSettings>(File.ReadAllText(ProfilesManagerSettingsPath), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
-
-                }
-
-                catch (Exception exc)
-
-                {
-
-                    Global.logger.LogLine("Exception occured while loading Profiles Settings.\nException:" + exc, Logging_Level.Error);
-
-                    SaveSettings();
-
-                }
-
-            }
-
-            else
-
-                SaveSettings();*/
-
-
-
-            foreach (var kvp in Events)
-
-            {
-
-                if (!Global.Configuration.ProfileOrder.Contains(kvp.Key) && kvp.Value is ProfileManager)
-
-                    Global.Configuration.ProfileOrder.Add(kvp.Key);
-
-            }
-
-
-
-            foreach(string key in Global.Configuration.ProfileOrder.ToList())
-
-            {
-
-                if (!Events.ContainsKey(key) || !(Events[key] is ProfileManager))
-
-                    Global.Configuration.ProfileOrder.Remove(key);
-
-            }
-
-
-
-            Global.Configuration.ProfileOrder.Remove("desktop");
-
-            Global.Configuration.ProfileOrder.Insert(0, "desktop");
-
-        }
-
-
-
-        /*public static void SaveSettings()
-
-        {
-
-            if (Settings == null)
-
-                Settings = new ProfilesManagerSettings();
-
-
-
-            File.WriteAllText(ProfilesManagerSettingsPath, JsonConvert.SerializeObject(Settings, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }));
-
-        }*/
-
-
-
-        public void SaveAll()
-
-        {
-
-            //SaveSettings();
-
-
-
-            foreach(var profile in Events)
-
-            {
-
-                if (profile.Value is ProfileManager)
-
-                    ((ProfileManager)profile.Value).SaveProfiles();
-
-            }
-
-        }
-
-
-
-        public bool RegisterProfile(LightEventConfig config)
-
-        {
-
-            return RegisterEvent(new ProfileManager(config));
-
-        }
-
-
-
-        private List<string> GetEventTable(LightEventType type)
-
-        {
-
-            List<string> events;
-
-            switch (type)
-
-            {
-
-                case LightEventType.Normal:
-
-                    events = Normal;
-
-                    break;
-
-                case LightEventType.Overlay:
-
-                    events = Overlays;
-
-                    break;
-
-                case LightEventType.Underlay:
-
-                    events = Underlays;
-
-                    break;
-
-                default:
-
-                    throw new NotImplementedException();
-
-            }
-
-            return events;
-
-        }
-
-
-
-        private bool InsertLightEvent(ILightEvent lightEvent, LightEventType? old = null)
-
-        {
-
-            if (old == null)
-
-            {
-
-                lightEvent.Config.PropertyChanged += LightEvent_PropertyChanged;
-
-            }
-
-            else
-
-            {
-
-                var oldEvents = GetEventTable((LightEventType)old);
-
-                oldEvents.Remove(lightEvent.Config.ID);
-
-            }
-
-
-
-            var events = GetEventTable(lightEvent.Config.Type);
-
-
-
-            events.Add(lightEvent.Config.ID);
-
-
-
-            return true;
-
-        }
-
-
-
-        private void LightEvent_PropertyChanged(object sender, PropertyChangedExEventArgs e)
-
-        {
-
-            ILightEvent lightEvent = (ILightEvent)sender;
-
-            if (e.PropertyName.Equals(nameof(LightEventConfig.Type)))
-
-            {
-
-                LightEventType old = (LightEventType)e.OldValue;
-
-                LightEventType newVal = (LightEventType)e.NewValue;
-
-
-
-                if (!old.Equals(newVal))
-
-                {
-
-                    InsertLightEvent(lightEvent, old);
-
-                }
-
-            }
-
-        }
-
-
-
-        public bool RegisterEvent(ILightEvent @event)
-
-        {
-
-            string key = @event.Config.ID;
-
-            if (string.IsNullOrWhiteSpace(key) || Events.ContainsKey(key))
-
-                return false;
-
-
-
-            Events.Add(key, @event);
-
-
-
-            if (@event.Config.ProcessNames != null)
-
-            {
-
-                foreach (string exe in @event.Config.ProcessNames)
-
-                {
-
-                    if (!exe.Equals(key))
-
-                        EventProcesses.Add(exe, key);
-
-                }
-
-            }
-
-
-
-            if (!String.IsNullOrWhiteSpace(@event.Config.AppID))
-
-                EventAppIDs.Add(@event.Config.AppID, key);
-
-
-
-            if (@event is ProfileManager)
-
-            {
-
-                if (!Global.Configuration.ProfileOrder.Contains(key))
-
-                    Global.Configuration.ProfileOrder.Add(key);
-
-            }
-
-
-
-            this.InsertLightEvent(@event);
-
-
-
-            if (Initialized)
-
-                @event.Initialize();
-
-
-
-            return true;
-
-        }
-
-
-
-        public void RegisterProfiles(List<LightEventConfig> profiles)
-
-        {
-
-            foreach (var profile in profiles)
-
-            {
-
-                RegisterProfile(profile);
-
-            }
-
-        }
-
-
-
-        public void RegisterEvents(List<ILightEvent> profiles)
-
-        {
-
-            foreach (var profile in profiles)
-
-            {
-
-                RegisterEvent(profile);
-
-            }
-
-        }
-
-
-
-        public void RemoveGenericProfile(string key)
-
-        {
-
-            if (Events.ContainsKey(key))
-
-            {
-
-                if (!(Events[key] is GenericApplicationProfileManager))
-
-                    return;
-
-                GenericApplicationProfileManager profile = (GenericApplicationProfileManager)Events[key];
-
-                string path = profile.GetProfileFolderPath();
-
-                if (Directory.Exists(path))
-
-                    Directory.Delete(path, true);
-
-
-
-                Events.Remove(key);
-
-                Global.Configuration.ProfileOrder.Remove(key);
-
-
-
-                //SaveSettings();
-
-            }
-
-        }
-
-
-
-        public ILightEvent GetProfileFromProcess(string process)
-
-        {
-
-            if (EventProcesses.ContainsKey(process))
-
-                return Events[EventProcesses[process]];
-
-            else if (Events.ContainsKey(process))
-
-                return Events[process];
-
-            else if (Events.ContainsKey(process))
-
-                return Events[process];
-
-
-
-
-
-            return null;
-
-        }
-
-
-
-        public ILightEvent GetProfileFromAppID(string appid)
-
-        {
-
-            if (EventAppIDs.ContainsKey(appid))
-
-                return Events[EventAppIDs[appid]];
-
-            else if (Events.ContainsKey(appid))
-
-                return Events[appid];
-
-            else if (Events.ContainsKey(appid))
-
-                return Events[appid];
-
-
-
-            return null;
-
-        }
-
-
-
-        public void RegisterLayerHandlers(List<LayerHandlerEntry> layers, bool @default = true)
-
-        {
-
-            foreach(var layer in layers)
-
-            {
-
-                RegisterLayerHandler(layer, @default);
-
-            }
-
-        }
-
-
-
-        public bool RegisterLayerHandler(LayerHandlerEntry entry, bool @default = true)
-
-        {
-
-            if (LayerHandlers.ContainsKey(entry.Key) || DefaultLayerHandlers.Contains(entry.Key))
-
-                return false;
-
-
-
-            LayerHandlers.Add(entry.Key, entry);
-
-
-
-            if (@default)
-
-                DefaultLayerHandlers.Add(entry.Key);
-
-
-
-            return true;
-
-        }
-
-
-
-        public bool RegisterLayerHandler(string key, string title, Type type, bool @default = true)
-
-        {
-
-            return RegisterLayerHandler(new LayerHandlerEntry(key, title, type));
-
-        }
-
-
-
-        public Type GetLayerHandlerType(string key)
-
-        {
-
-            return LayerHandlers.ContainsKey(key) ? LayerHandlers[key].Type : null;
-
-        }
-
-
-
-        public ILayerHandler GetLayerHandlerInstance(LayerHandlerEntry entry)
-
-        {
-
-            return (ILayerHandler)Activator.CreateInstance(entry.Type);
-
-        }
-
-
-
-        public ILayerHandler GetLayerHandlerInstance(string key)
-
-        {
-
-            if (LayerHandlers.ContainsKey(key))
-
-            {
-
-                return GetLayerHandlerInstance(LayerHandlers[key]);
-
-            }
-
-
-
-
-
-            return null;
-
-        }
-
-
-
-        private Timer updateTimer;
-
-
-
-        private const int defaultTimerInterval = 33;
-
-        private int timerInterval = defaultTimerInterval;
-
-
-
-        private long nextProcessNameUpdate;
-
-        private long currentTick;
-
-        private string previewModeProfileKey = "";
-
-
-
-        private List<TimedListObject> overlays = new List<TimedListObject>();
-
-        private Event_Idle idle_e = new Event_Idle();
-
-
-
-        public string PreviewProfileKey { get { return previewModeProfileKey; } set { previewModeProfileKey = value ?? string.Empty; } }
-
-
-
-        private void InitUpdate()
-
-        {
-
-            updateTimer = new System.Threading.Timer(g => {
-
-                Stopwatch watch = new Stopwatch();
-
-                watch.Start();
-
-                try
-
-                {
-
-                    Update();
-
-                }
-
-                catch (Exception exc)
-
-                {
-
-                    Global.logger.LogLine("ProfilesManager.Update() Exception, " + exc, Logging_Level.Error);
-
-                }
-
-
-
-                watch.Stop();
-
-                currentTick += timerInterval + watch.ElapsedMilliseconds;
-
-                updateTimer?.Change(Math.Max(timerInterval, 0), Timeout.Infinite);
-
-            }, null, 0, System.Threading.Timeout.Infinite);
-
-            GC.KeepAlive(updateTimer);
-
-        }
-
-
-
-        private void UpdateProcess()
-
-        {
-
-            if (Global.Configuration.detection_mode == Settings.ApplicationDetectionMode.ForegroroundApp && (currentTick >= nextProcessNameUpdate))
-
-            {
-
-                processMonitor.GetActiveWindowsProcessname();
-
-                nextProcessNameUpdate = currentTick + 1000L;
-
-            }
-
-        }
-
-
-
-        private void UpdateIdleEffects(EffectsEngine.EffectFrame newFrame)
-
-        {
-
-            tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
-
-            Int32 IdleTime;
-
-            LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
-
-            LastInput.dwTime = 0;
-
-
-
-            if (ActiveProcessMonitor.GetLastInputInfo(ref LastInput))
-
-            {
-
-                IdleTime = System.Environment.TickCount - LastInput.dwTime;
-
-
-
-                if (IdleTime >= Global.Configuration.idle_delay * 60 * 1000)
-
-                {
-
-                    if (!(Global.Configuration.time_based_dimming_enabled &&
-
-                    Utils.Time.IsCurrentTimeBetween(Global.Configuration.time_based_dimming_start_hour, Global.Configuration.time_based_dimming_start_minute, Global.Configuration.time_based_dimming_end_hour, Global.Configuration.time_based_dimming_end_minute))
-
-                    )
-
-                    {
-
-                        idle_e.UpdateLights(newFrame);
-
-                    }
-
-                }
-
-            }
-
-        }
-
-
-
-        private void Update()
-
-        {
-
-            //Blackout. TODO: Cleanup this a bit. Maybe push blank effect frame to keyboard incase it has existing stuff displayed
-
-            if ((Global.Configuration.time_based_dimming_enabled &&
-
-               Utils.Time.IsCurrentTimeBetween(Global.Configuration.time_based_dimming_start_hour, Global.Configuration.time_based_dimming_start_minute, Global.Configuration.time_based_dimming_end_hour, Global.Configuration.time_based_dimming_end_minute)))
-
-                return;
-
-
-
-            UpdateProcess();
-
-
-
-            string process_name = System.IO.Path.GetFileName(processMonitor.ProcessPath).ToLowerInvariant();
-
-
-
-            EffectsEngine.EffectFrame newFrame = new EffectsEngine.EffectFrame();
-
-
-
-            foreach(var underlay in Underlays)
-
-            {
-
-                ILightEvent @event = Events[underlay];
-
-                if (@event.IsEnabled && (@event.Config.ProcessNames == null || ProcessUtils.AnyProcessExists(@event.Config.ProcessNames)))
-
-                    @event.UpdateLights(newFrame);
-
-            }
-
-
-
-            //TODO: Move these IdleEffects to an event
-
-            //this.UpdateIdleEffects(newFrame);
-
-
-
-            ILightEvent profile = null;
-
-            ILightEvent tempProfile = null;
-
-            //Global.logger.LogLine(process_name);
-
-            if (!Global.Configuration.excluded_programs.Contains(process_name)) {
-
-                //TODO: GetProfile that checks based on event type
-
-                if ((((tempProfile = GetProfileFromProcess(process_name)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
-
-                    || (((tempProfile = GetProfileFromProcess(previewModeProfileKey)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
-
-                    || (Global.Configuration.allow_wrappers_in_background && Global.net_listener != null && Global.net_listener.IsWrapperConnected && ((tempProfile = GetProfileFromProcess(Global.net_listener.WrappedProcess)) != null) && tempProfile.Config.Type == LightEventType.Normal && tempProfile.IsEnabled)
-
-                )
-
-                    profile = tempProfile;
-
-            }
-
-
-
-            profile = profile ?? DesktopProfile;
-
-
-
-            timerInterval = (profile as ProfileManager)?.Config?.UpdateInterval ?? defaultTimerInterval;
-
-
-
-            //Check if any keybinds have been triggered
-
-            foreach(var prof in (profile as ProfileManager).Profiles)
-
-            {
-
-                if(prof.TriggerKeybind.IsPressed() && !(profile as ProfileManager).Settings.ProfileName.Equals(prof.ProfileName))
-
-                {
-
-                    (profile as ProfileManager).SwitchToProfile(prof);
-
-                    break;
-
-                }
-
-            }
-
-
-
-            Global.dev_manager.InitializeOnce();
-
-            profile.UpdateLights(newFrame);
-
-
-
-            foreach (var overlay in Overlays)
-
-            {
-
-                ILightEvent @event = Events[overlay];
-
-                if (@event.IsEnabled && (@event.Config.ProcessNames == null || ProcessUtils.AnyProcessExists(@event.Config.ProcessNames)))
-
-                    @event.UpdateLights(newFrame);
-
-            }
-
-
-
-            //Add overlays
-
-            TimedListObject[] overlay_events = overlays.ToArray();
-
-            foreach (TimedListObject evnt in overlay_events)
-
-            {
-
-                if ((evnt.item as LightEvent).IsEnabled)
-
-                    (evnt.item as LightEvent).UpdateLights(newFrame);
-
-            }
-
-
-
-            Global.effengine.PushFrame(newFrame);
-
-        }
-
-
-
-        public void GameStateUpdate(IGameState gs)
-
-        {
-
-            //Debug.WriteLine("Received gs!");
-
-
-
-            //Global.logger.LogLine(gs.ToString(), Logging_Level.None, false);
-
-
-
-            //UpdateProcess();
-
-
-
-            string process_name = System.IO.Path.GetFileName(processMonitor.ProcessPath).ToLowerInvariant();
-
-
-
-            //EffectsEngine.EffectFrame newFrame = new EffectsEngine.EffectFrame();
-
-
-
-            try
-
-            {
-
-                ILightEvent profile = this.GetProfileFromProcess(process_name);
-
-
-
-                JObject provider = Newtonsoft.Json.Linq.JObject.Parse(gs.GetNode("provider"));
-
-                string appid = provider.GetValue("appid").ToString();
-
-                string name = provider.GetValue("name").ToString().ToLowerInvariant();
-
-
-
-                if (profile != null || (profile = GetProfileFromAppID(appid)) != null || (profile = GetProfileFromProcess(name)) != null)
-
-                    profile.SetGameState((IGameState)Activator.CreateInstance(profile.Config.GameStateType, gs));
-
-                else if (gs is GameState_Wrapper && Global.Configuration.allow_all_logitech_bitmaps)
-
-                {
-
-                    string gs_process_name = Newtonsoft.Json.Linq.JObject.Parse(gs.GetNode("provider")).GetValue("name").ToString().ToLowerInvariant();
-
-
-
-                    profile = profile ?? GetProfileFromProcess(gs_process_name);
-
-
-
-                    if (profile == null)
-
-                    {
-
-                        Events.Add(gs_process_name, new GameEvent_Aurora_Wrapper());
-
-                        profile = Events[gs_process_name];
-
-                    }
-
-
-
-                    profile.SetGameState(gs);
-
-                }
-
-
-
-                //UpdateIdleEffects(newFrame);
-
-            }
-
-            catch (Exception e)
-
-            {
-
-                Global.logger.LogLine("Exception during GameStateUpdate(), error: " + e, Logging_Level.Warning);
-
-            }
-
-        }
-
-
-
-        public void ResetGameState(string process)
-
-        {
-
-            ILightEvent profile;
-
-            if (((profile = GetProfileFromProcess(process)) != null))
-
-                profile.ResetGameState();
-
-        }
-
-
-
-        public void AddOverlayForDuration(LightEvent overlay_event, int duration, bool isUnique = true)
-
-        {
-
-            if (isUnique)
-
-            {
-
-                TimedListObject[] overlays_array = overlays.ToArray();
-
-                bool isFound = false;
-
-
-
-                foreach (TimedListObject obj in overlays_array)
-
-                {
-
-                    if (obj.item.GetType() == overlay_event.GetType())
-
-                    {
-
-                        isFound = true;
-
-                        obj.AdjustDuration(duration);
-
-                        break;
-
-                    }
-
-                }
-
-
-
-                if (!isFound)
-
-                {
-
-                    overlays.Add(new TimedListObject(overlay_event, duration, overlays));
-
-                }
-
-            }
-
-            else
-
-            {
-
-                overlays.Add(new TimedListObject(overlay_event, duration, overlays));
-
-            }
-
-        }
-
-
-
-        public void Dispose()
-
-        {
-
-            if(updateTimer != null)
-
-            {
-
-                updateTimer.Dispose();
-
-                updateTimer = null;
-
-            }
-
-        }
-
-    }
-
-}
-
+        }
+
+        public void ResetGameState(string process)
+        {
+            ILightEvent profile;
+            if (((profile = GetProfileFromProcess(process)) != null))
+                profile.ResetGameState();
+        }
+
+        public void AddOverlayForDuration(LightEvent overlay_event, int duration, bool isUnique = true)
+        {
+            if (isUnique)
+            {
+                TimedListObject[] overlays_array = overlays.ToArray();
+                bool isFound = false;
+
+                foreach (TimedListObject obj in overlays_array)
+                {
+                    if (obj.item.GetType() == overlay_event.GetType())
+                    {
+                        isFound = true;
+                        obj.AdjustDuration(duration);
+                        break;
+                    }
+                }
+
+                if (!isFound)
+                {
+                    overlays.Add(new TimedListObject(overlay_event, duration, overlays));
+                }
+            }
+            else
+            {
+                overlays.Add(new TimedListObject(overlay_event, duration, overlays));
+            }
+        }
+
+        public void Dispose()
+        {
+            if (updateTimer != null)
+            {
+                updateTimer.Dispose();
+                updateTimer = null;
+            }
+        }
+    }
+}


Remove unnecessary explicit static cctors

Let these types be marked beforefieldinit

--- src/mscorlib/src/System/Threading/ThreadPool.cs
+++ src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -56,10 +56,6 @@
         public static bool enableWorkerTracking;

         public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
-
-        static ThreadPoolGlobals()
-        {
-        }
     }

     internal sealed class ThreadPoolWorkQueue
@@ -969,8 +965,6 @@

     internal sealed class QueueUserWorkItemCallback : IThreadPoolWorkItem
     {
-        static QueueUserWorkItemCallback() {}
-
         private WaitCallback callback;
         private ExecutionContext context;
         private Object state;
@@ -1041,8 +1035,6 @@

     internal sealed class QueueUserWorkItemCallbackDefaultContext : IThreadPoolWorkItem
     {
-        static QueueUserWorkItemCallbackDefaultContext() { }
-
         private WaitCallback callback;
         private Object state;

@@ -1102,8 +1094,6 @@

     internal class _ThreadPoolWaitOrTimerCallback
     {
-        static _ThreadPoolWaitOrTimerCallback() {}
-
         WaitOrTimerCallback _waitOrTimerCallback;
         ExecutionContext _executionContext;
         Object _state;


[Toolkit.Game] Fix DrawInstanced indirect overload

Should call DrawInstancedIndirect instead of
DrawIndexedInstancedIndirect

--- Source/Toolkit/SharpDX.Toolkit.Graphics/GraphicsDevice.cs
+++ Source/Toolkit/SharpDX.Toolkit.Graphics/GraphicsDevice.cs
@@ -770,7 +770,7 @@
             SetupInputLayout();

             PrimitiveType = primitiveType;
-            Context.DrawIndexedInstancedIndirect(argumentsBuffer, alignedByteOffsetForArgs);
+            Context.DrawInstancedIndirect(argumentsBuffer, alignedByteOffsetForArgs);
         }

         /// <summary>


Add ThreadPool.QueueUserWorkItem(..., bool preferLocal)

--- src/mscorlib/src/System/Threading/ThreadPool.cs
+++ src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -1268,9 +1268,12 @@
         }

         public static bool QueueUserWorkItem(WaitCallback callBack) =>
-            QueueUserWorkItem(callBack, null);
-
-        public static bool QueueUserWorkItem(WaitCallback callBack, object state)
+            QueueUserWorkItem(callBack, null, preferLocal: false);
+
+        public static bool QueueUserWorkItem(WaitCallback callBack, object state) =>
+            QueueUserWorkItem(callBack, state, preferLocal: false);
+
+        public static bool QueueUserWorkItem(WaitCallback callBack, object state, bool preferLocal)
         {
             if (callBack == null)
             {
@@ -1285,7 +1288,7 @@
                 new QueueUserWorkItemCallbackDefaultContext(callBack, state) :
                 (IThreadPoolWorkItem)new QueueUserWorkItemCallback(callBack, state, context);

-            ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true);
+            ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal);

             return true;
         }


Use ConcurrentQueue<T> in ThreadPool

Use ConcurrentQueue<T> in ThreadPool

Use the same ConcurrentQueue<T> now being used in corefx in ThreadPool instead of ThreadPool's custom queue implementation (which was close in design to the old ConcurrentQueue<T> implementation).

--- src/mscorlib/src/System/Threading/ThreadPool.cs
+++ src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -35,6 +35,7 @@
     using System.Runtime.CompilerServices;
     using System.Runtime.ConstrainedExecution;
     using System.Runtime.InteropServices;
+    using System.Collections.Concurrent;
     using System.Collections.Generic;
     using System.Diagnostics;
     using System.Diagnostics.Contracts;
@@ -408,140 +409,8 @@
             }
         }

-        internal class QueueSegment
-        {
-            // Holds a segment of the queue.  Enqueues/Dequeues start at element 0, and work their way up.
-            internal readonly IThreadPoolWorkItem[] nodes;
-            private const int QueueSegmentLength = 256;
-
-            // Holds the indexes of the lowest and highest valid elements of the nodes array.
-            // The low index is in the lower 16 bits, high index is in the upper 16 bits.
-            // Use GetIndexes and CompareExchangeIndexes to manipulate this.
-            private volatile int indexes;
-
-            // The next segment in the queue.
-            public volatile QueueSegment Next;
-
-
-            const int SixteenBits = 0xffff;
-
-            void GetIndexes(out int upper, out int lower)
-            {
-                int i = indexes;
-                upper = (i >> 16) & SixteenBits;
-                lower = i & SixteenBits;
-
-                Debug.Assert(upper >= lower);
-                Debug.Assert(upper <= nodes.Length);
-                Debug.Assert(lower <= nodes.Length);
-                Debug.Assert(upper >= 0);
-                Debug.Assert(lower >= 0);
-            }
-
-            bool CompareExchangeIndexes(ref int prevUpper, int newUpper, ref int prevLower, int newLower)
-            {
-                Debug.Assert(newUpper >= newLower);
-                Debug.Assert(newUpper <= nodes.Length);
-                Debug.Assert(newLower <= nodes.Length);
-                Debug.Assert(newUpper >= 0);
-                Debug.Assert(newLower >= 0);
-                Debug.Assert(newUpper >= prevUpper);
-                Debug.Assert(newLower >= prevLower);
-                Debug.Assert(newUpper == prevUpper ^ newLower == prevLower);
-
-                int oldIndexes = (prevUpper << 16) | (prevLower & SixteenBits);
-                int newIndexes = (newUpper << 16) | (newLower & SixteenBits);
-                int prevIndexes = Interlocked.CompareExchange(ref indexes, newIndexes, oldIndexes);
-                prevUpper = (prevIndexes >> 16) & SixteenBits;
-                prevLower = prevIndexes & SixteenBits;
-                return prevIndexes == oldIndexes;
-            }
-
-            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
-            public QueueSegment()
-            {
-                Debug.Assert(QueueSegmentLength <= SixteenBits);
-                nodes = new IThreadPoolWorkItem[QueueSegmentLength];
-            }
-
-
-            public bool IsUsedUp()
-            {
-                int upper, lower;
-                GetIndexes(out upper, out lower);
-                return (upper == nodes.Length) &&
-                       (lower == nodes.Length);
-            }
-
-            public bool TryEnqueue(IThreadPoolWorkItem node)
-            {
-                //
-                // If there's room in this segment, atomically increment the upper count (to reserve
-                // space for this node), then store the node.
-                // Note that this leaves a window where it will look like there is data in that
-                // array slot, but it hasn't been written yet.  This is taken care of in TryDequeue
-                // with a busy-wait loop, waiting for the element to become non-null.  This implies
-                // that we can never store null nodes in this data structure.
-                //
-                Debug.Assert(null != node);
-
-                int upper, lower;
-                GetIndexes(out upper, out lower);
-
-                while (true)
-                {
-                    if (upper == nodes.Length)
-                        return false;
-
-                    if (CompareExchangeIndexes(ref upper, upper + 1, ref lower, lower))
-                    {
-                        Debug.Assert(Volatile.Read(ref nodes[upper]) == null);
-                        Volatile.Write(ref nodes[upper], node);
-                        return true;
-                    }
-                }
-            }
-
-            [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
-            public bool TryDequeue(out IThreadPoolWorkItem node)
-            {
-                //
-                // If there are nodes in this segment, increment the lower count, then take the
-                // element we find there.
-                //
-                int upper, lower;
-                GetIndexes(out upper, out lower);
-
-                while(true)
-                {
-                    if (lower == upper)
-                    {
-                        node = null;
-                        return false;
-                    }
-
-                    if (CompareExchangeIndexes(ref upper, upper, ref lower, lower + 1))
-                    {
-                        // It's possible that a concurrent call to Enqueue hasn't yet
-                        // written the node reference to the array.  We need to spin until
-                        // it shows up.
-                        SpinWait spinner = new SpinWait();
-                        while ((node = Volatile.Read(ref nodes[lower])) == null)
-                            spinner.SpinOnce();
-
-                        // Null-out the reference so the object can be GC'd earlier.
-                        nodes[lower] = null;
-
-                        return true;
-                    }
-                }
-            }
-        }
-
-        // The head and tail of the queue.  We enqueue to the head, and dequeue from the tail.
-        internal volatile QueueSegment queueHead;
-        internal volatile QueueSegment queueTail;
         internal bool loggingEnabled;
+        internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>();

         internal static readonly SparseArray<WorkStealingQueue> allThreadQueues = new SparseArray<WorkStealingQueue>(16);

@@ -549,7 +418,6 @@

         public ThreadPoolWorkQueue()
         {
-            queueTail = queueHead = new QueueSegment();
             loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer);
         }

@@ -615,18 +483,7 @@
             }
             else
             {
-                QueueSegment head = queueHead;
-
-                while (!head.TryEnqueue(callback))
-                {
-                    Interlocked.CompareExchange(ref head.Next, new QueueSegment(), null);
-
-                    while (head.Next != null)
-                    {
-                        Interlocked.CompareExchange(ref queueHead, head.Next, head);
-                        head = queueHead;
-                    }
-                }
+                workItems.Enqueue(callback);
             }

             EnsureThreadRequested();
@@ -652,24 +509,9 @@

             if (null == callback)
             {
-                QueueSegment tail = queueTail;
-                while (true)
-                {
-                    if (tail.TryDequeue(out callback))
-                    {
-                        Debug.Assert(null != callback);
-                        break;
-                    }
-
-                    if (null == tail.Next || !tail.IsUsedUp())
-                    {
-                        break;
-                    }
-                    else
-                    {
-                        Interlocked.CompareExchange(ref queueTail, tail.Next, tail);
-                        tail = queueTail;
-                    }
+                if (workItems.TryDequeue(out callback))
+                {
+                    Debug.Assert(null != callback);
                 }
             }

@@ -1632,42 +1474,25 @@
         // Get all workitems.  Called by TaskScheduler in its debugger hooks.
         internal static IEnumerable<IThreadPoolWorkItem> GetQueuedWorkItems()
         {
-            return EnumerateQueuedWorkItems(ThreadPoolWorkQueue.allThreadQueues.Current, ThreadPoolGlobals.workQueue.queueTail);
-        }
-
-        internal static IEnumerable<IThreadPoolWorkItem> EnumerateQueuedWorkItems(ThreadPoolWorkQueue.WorkStealingQueue[] wsQueues, ThreadPoolWorkQueue.QueueSegment globalQueueTail)
-        {
-            if (wsQueues != null)
-            {
-                // First, enumerate all workitems in thread-local queues.
-                foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in wsQueues)
-                {
-                    if (wsq != null && wsq.m_array != null)
-                    {
-                        IThreadPoolWorkItem[] items = wsq.m_array;
-                        for (int i = 0; i < items.Length; i++)
-                        {
-                            IThreadPoolWorkItem item = items[i];
-                            if (item != null)
-                                yield return item;
-                        }
-                    }
-                }
-            }
-
-            if (globalQueueTail != null)
-            {
-                // Now the global queue
-                for (ThreadPoolWorkQueue.QueueSegment segment = globalQueueTail;
-                    segment != null;
-                    segment = segment.Next)
-                {
-                    IThreadPoolWorkItem[] items = segment.nodes;
+            // Enumerate global queue
+            foreach (IThreadPoolWorkItem workItem in ThreadPoolGlobals.workQueue.workItems)
+            {
+                yield return workItem;
+            }
+
+            // Enumerate each local queue
+            foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.allThreadQueues.Current)
+            {
+                if (wsq != null && wsq.m_array != null)
+                {
+                    IThreadPoolWorkItem[] items = wsq.m_array;
                     for (int i = 0; i < items.Length; i++)
                     {
                         IThreadPoolWorkItem item = items[i];
                         if (item != null)
+                        {
                             yield return item;
+                        }
                     }
                 }
             }
@@ -1675,13 +1500,20 @@

         internal static IEnumerable<IThreadPoolWorkItem> GetLocallyQueuedWorkItems()
         {
-            return EnumerateQueuedWorkItems(new ThreadPoolWorkQueue.WorkStealingQueue[] { ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue }, null);
-        }
-
-        internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems()
-        {
-            return EnumerateQueuedWorkItems(null, ThreadPoolGlobals.workQueue.queueTail);
-        }
+            ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue;
+            if (wsq != null && wsq.m_array != null)
+            {
+                IThreadPoolWorkItem[] items = wsq.m_array;
+                for (int i = 0; i < items.Length; i++)
+                {
+                    IThreadPoolWorkItem item = items[i];
+                    if (item != null)
+                        yield return item;
+                }
+            }
+        }
+
+        internal static IEnumerable<IThreadPoolWorkItem> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems;

         private static object[] ToObjectArray(IEnumerable<IThreadPoolWorkItem> workitems)
         {


Modified usage of MemoryStream

Modified usage of MemoryStream

--- SnowyImageCopy/Models/ImageManager.cs
+++ SnowyImageCopy/Models/ImageManager.cs
@@ -73,11 +73,10 @@
 			try
 			{
 				using (var ms = new MemoryStream())
-				using (var writer = new BinaryWriter(ms))
-				{
-					writer.Write(bytes);
-
-					return await Task.Run(() => ReadThumbnailFromExifByImaging(ms));
+				{
+					return await ms.WriteAsync(bytes, 0, bytes.Length)
+						.ContinueWith(_ => ReadThumbnailFromExifByImaging(ms))
+						.ConfigureAwait(false);
 				}
 			}
 			catch (Exception ex)
@@ -136,11 +135,10 @@
 			try
 			{
 				using (var ms = new MemoryStream())
-				using (var writer = new BinaryWriter(ms))
-				{
-					writer.Write(bytes);
-
-					return await Task.Run(() => CreateThumbnailFromImageUniform(ms));
+				{
+					return await ms.WriteAsync(bytes, 0, bytes.Length)
+						.ContinueWith(_ => CreateThumbnailFromImageUniform(ms))
+						.ConfigureAwait(false);
 				}
 			}
 			catch (Exception ex)
@@ -179,10 +177,8 @@
 				var propItem = drawingImage.GetPropertyItem(thumbnailDataId);

 				using (var ms = new MemoryStream())
-				using (var writer = new BinaryWriter(ms))
-				{
-					writer.Write(propItem.Value);
-
+				{
+					ms.Write(propItem.Value, 0, propItem.Value.Length);
 					return ConvertStreamToBitmapImage(ms);
 				}
 			}
@@ -414,9 +410,8 @@
 			try
 			{
 				using (var ms = new MemoryStream())
-				using (var writer = new BinaryWriter(ms))
-				{
-					writer.Write(bytes);
+				{
+					await ms.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

 					if (willReadExif)
 						await Task.Run(() => ReflectOrientationToStream(ms));
@@ -449,9 +444,8 @@
 			try
 			{
 				using (var ms = new MemoryStream())
-				using (var writer = new BinaryWriter(ms))
-				{
-					writer.Write(bytes);
+				{
+					await ms.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

 					if (willReadExif)
 						await Task.Run(() => ReflectOrientationToStream(ms));
@@ -474,7 +468,7 @@
 		/// Reflect orientation in Exif metadata to image.
 		/// </summary>
 		/// <param name="stream">Target stream</param>
-		private static void ReflectOrientationToStream(MemoryStream stream)
+		private static void ReflectOrientationToStream(Stream stream)
 		{
 			if (0 < stream.Position)
 				stream.Seek(0, SeekOrigin.Begin);


Added client store and user store to factory

--- Source/Core.MongoDb/ServiceFactory.cs
+++ Source/Core.MongoDb/ServiceFactory.cs
@@ -5,25 +5,33 @@
 using System.Threading.Tasks;
 using MongoDB.Bson;
 using MongoDB.Driver;
+using Thinktecture.IdentityServer.Core.Configuration;
+using Thinktecture.IdentityServer.Core.Services;

 namespace IdentityServer.Core.MongoDb
 {
-    public class ServiceFactory
+    public class ServiceFactory : IdentityServerServiceFactory
     {
         private MongoDatabase _db;

-        public ServiceFactory(): this("mongodb://localhost")
+        public ServiceFactory(Registration<IUserService> userService)
+            : this("mongodb://localhost", userService)
         {}
-        public ServiceFactory(string mongoUrl):this(DefaultSettings(mongoUrl),
-            DefaultStoreSettings())
+        public ServiceFactory(string mongoUrl, Registration<IUserService> userService)
+            : this(DefaultSettings(mongoUrl),
+            DefaultStoreSettings(),userService)
         {

         }
-        public ServiceFactory(MongoClientSettings settings, StoreSettings storeSettings)
+        public ServiceFactory(MongoClientSettings settings, StoreSettings storeSettings, Registration<IUserService> userService)
         {
             var client = new MongoClient(settings);
             var server = client.GetServer();
             _db = server.GetDatabase(storeSettings.Database);
+            UserService = userService;
+            ClientStore =
+                Registration.RegisterSingleton<IClientStore>(new ClientStore(_db, storeSettings.ClientCollection));
+
         }

         public static MongoClientSettings DefaultSettings(string mongoUrl)
@@ -43,5 +51,8 @@
                 ClientCollection = "clients"
             };
         }
+
     }
+
+
 }


Improve exception handling in AsyncQueue.

--- Source/MQTTnet/Internal/AsyncQueue.cs
+++ Source/MQTTnet/Internal/AsyncQueue.cs
@@ -7,15 +7,19 @@
 {
     public sealed class AsyncQueue<TItem> : IDisposable
     {
+        readonly object _syncRoot = new object();
         SemaphoreSlim _semaphore = new SemaphoreSlim(0);
         ConcurrentQueue<TItem> _queue = new ConcurrentQueue<TItem>();
-
+
         public int Count => _queue.Count;

         public void Enqueue(TItem item)
         {
-            _queue.Enqueue(item);
-            _semaphore?.Release();
+            lock (_syncRoot)
+            {
+                _queue.Enqueue(item);
+                _semaphore?.Release();
+            }
         }

         public async Task<AsyncQueueDequeueResult<TItem>> TryDequeueAsync(CancellationToken cancellationToken)
@@ -24,22 +28,37 @@
             {
                 try
                 {
-                    if (_semaphore == null)
+                    Task task;
+                    lock (_syncRoot)
+                    {
+                        if (_semaphore == null)
+                        {
+                            return new AsyncQueueDequeueResult<TItem>(false, default);
+                        }
+
+                        task = _semaphore.WaitAsync(cancellationToken);
+                    }
+
+                    await task.ConfigureAwait(false);
+
+                    if (cancellationToken.IsCancellationRequested)
                     {
                         return new AsyncQueueDequeueResult<TItem>(false, default);
                     }

-                    await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
-                    cancellationToken.ThrowIfCancellationRequested();
+                    if (_queue.TryDequeue(out var item))
+                    {
+                        return new AsyncQueueDequeueResult<TItem>(true, item);
+                    }
+                }
+                catch (ArgumentNullException)
+                {
+                    // The semaphore throws this internally sometimes.
+                    return new AsyncQueueDequeueResult<TItem>(false, default);
                 }
                 catch (OperationCanceledException)
                 {
                     return new AsyncQueueDequeueResult<TItem>(false, default);
-                }
-
-                if (_queue.TryDequeue(out var item))
-                {
-                    return new AsyncQueueDequeueResult<TItem>(true, item);
                 }
             }

@@ -63,8 +82,11 @@

         public void Dispose()
         {
-            _semaphore?.Dispose();
-            _semaphore = null;
+            lock (_syncRoot)
+            {
+                _semaphore?.Dispose();
+                _semaphore = null;
+            }
         }
     }
 }


Refactered method to extract logic to one method.

--- Source/MSBuild.Community.Tasks/Zip.cs
+++ Source/MSBuild.Community.Tasks/Zip.cs
@@ -238,10 +238,7 @@
                             if (Directory.Exists(name))
                             {
                                 var directoryEntry = zip.AddDirectory(name, directoryPathInArchive);
-                                if (!MinimalLogging)
-                                {
-                                    Log.LogMessage(Resources.ZipAdded, directoryEntry.FileName);
-                                }
+                                LogMessageIfNotMinimalLogging(Resources.ZipAdded, directoryEntry.FileName);

                                 continue;
                             }
@@ -257,10 +254,7 @@

                         var entry = zip.AddFile(name, directoryPathInArchive);

-                        if (!MinimalLogging)
-                        {
-                            Log.LogMessage(Resources.ZipAdded, entry.FileName);
-                        }
+                        LogMessageIfNotMinimalLogging(Resources.ZipAdded, entry.FileName);
                     }

                     zip.Save(ZipFileName);
@@ -305,6 +299,14 @@
             return string.Join(Path.DirectorySeparatorChar.ToString(), relativePath.ToArray());
         }

+        private void LogMessageIfNotMinimalLogging(string message, params object[] messageArguments)
+        {
+            if (!MinimalLogging)
+            {
+                Log.LogMessage(message, messageArguments);
+            }
+        }
+
         #endregion Private Methods
     }
 }


Optimize locking for cancellation

Optimize locking for cancellation

--- Source/Miruken/Concurrency/Promise.cs
+++ Source/Miruken/Concurrency/Promise.cs
@@ -177,31 +177,38 @@
         {
             if (cancelled == null) return;

-            _lock.EnterUpgradeableReadLock();
-
             if (IsCompleted)
             {
-                _lock.ExitUpgradeableReadLock();
-
                 if (State == PromiseState.Cancelled)
                     cancelled(_exception as CancelledException);
-            }
-            else
-            {
-                _lock.EnterWriteLock();
-                try
-                {
-                    _rejected += (ex, s) =>
-                    {
-                        if (ex is CancelledException cancel)
-                            cancelled(cancel);
-                    };
-                }
-                finally
-                {
-                    _lock.ExitWriteLock();
-                    _lock.ExitUpgradeableReadLock();
-                }
+                return;
+            }
+
+            _lock.EnterUpgradeableReadLock();
+
+            if (IsCompleted)
+            {
+                _lock.ExitUpgradeableReadLock();
+
+                if (State == PromiseState.Cancelled)
+                    cancelled(_exception as CancelledException);
+                return;
+            }
+
+            _lock.EnterWriteLock();
+
+            try
+            {
+                _rejected += (ex, s) =>
+                {
+                    if (ex is CancelledException cancel)
+                        cancelled(cancel);
+                };
+            }
+            finally
+            {
+                _lock.ExitWriteLock();
+                _lock.ExitUpgradeableReadLock();
             }
         }

@@ -1111,7 +1118,7 @@
             return new Promise<R>(mode, owner);
         }

-        private void Subscribe(ResolveCallback resolve, RejectCallback reject)
+        protected void Subscribe(ResolveCallback resolve, RejectCallback reject)
         {
             if (IsCompleted)
             {


Update Details.cshtml

Update Details.cshtml

--- AstroPhotoGallery/AstroPhotoGallery/Views/Picture/Details.cshtml
+++ AstroPhotoGallery/AstroPhotoGallery/Views/Picture/Details.cshtml
@@ -23,6 +23,13 @@

+                <fieldset class="rating pull-right">
+                    <input type="radio" id="star5" name="rating" value="5" />5 stars
+                    <input type="radio" id="star4" name="rating" value="4" />4 stars
+                    <input type="radio" id="star3" name="rating" value="3" />3 stars
+                    <input type="radio" id="star2" name="rating" value="2" />2 stars
+                    <input type="radio" id="star1" name="rating" value="1" />1 star
+                </fieldset>

@@ -109,15 +116,6 @@

 <link href="~/Content/rating.css" rel="stylesheet" />
-<fieldset class="rating">
-    <legend>Please rate:</legend>
-    <input type="radio" id="star5" name="rating" value="5" />5 stars
-    <input type="radio" id="star4" name="rating" value="4" />4 stars
-    <input type="radio" id="star3" name="rating" value="3" />3 stars
-    <input type="radio" id="star2" name="rating" value="2" />2 stars
-    <input type="radio" id="star1" name="rating" value="1" />1 star
-</fieldset>
-

 @* <--- Comments examples --->


Update ShapeStyleDragAndDropListBox.cs

Update ShapeStyleDragAndDropListBox.cs

--- Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs
+++ Core2D.Wpf/Controls/Custom/Lists/ShapeStyleDragAndDropListBox.cs
@@ -31,7 +31,7 @@

             var previous = sg.Items;
             var next = array;
-            editor.project?.History?.Snapshot(previous, next, (p) => sg.Items = p);
+            editor.Project?.History?.Snapshot(previous, next, (p) => sg.Items = p);
             sg.Items = next;
         }
     }


修正判断相等可能不准确的问题

修正判断相等可能不准确的问题

--- DotMaysWind.Data/Command/Condition/SqlBasicParameterCondition.cs
+++ DotMaysWind.Data/Command/Condition/SqlBasicParameterCondition.cs
@@ -153,24 +153,32 @@
                 return false;
             }

-            if ((this._parameterOne != null && condition._parameterOne == null) || (this._parameterOne == null && condition._parameterOne != null))
-            {
-                return false;
-            }
-
-            if (this._parameterOne != null && condition._parameterOne != null && !this._parameterOne.Equals(condition._parameterOne))
-            {
-                return false;
-            }
-
-            if ((this._parameterTwo != null && condition._parameterTwo == null) || (this._parameterTwo == null && condition._parameterTwo != null))
-            {
-                return false;
-            }
-
-            if (this._parameterTwo != null && condition._parameterTwo != null && !this._parameterTwo.Equals(condition._parameterTwo))
-            {
-                return false;
+            Int32 paramCount = ((Byte)this._operator) / 100;
+
+            if (paramCount >= 1)
+            {
+                if ((this._parameterOne != null && condition._parameterOne == null) || (this._parameterOne == null && condition._parameterOne != null))
+                {
+                    return false;
+                }
+
+                if (this._parameterOne != null && condition._parameterOne != null && !this._parameterOne.Equals(condition._parameterOne))
+                {
+                    return false;
+                }
+            }
+
+            if (paramCount >= 2)
+            {
+                if ((this._parameterTwo != null && condition._parameterTwo == null) || (this._parameterTwo == null && condition._parameterTwo != null))
+                {
+                    return false;
+                }
+
+                if (this._parameterTwo != null && condition._parameterTwo != null && !this._parameterTwo.Equals(condition._parameterTwo))
+                {
+                    return false;
+                }
             }

             return true;


On Second Thought...

On Second Thought...

--- Ets.Mobile/Ets.Mobile.Agent/ScheduleTileUpdaterBackgroundTask.cs
+++ Ets.Mobile/Ets.Mobile.Agent/ScheduleTileUpdaterBackgroundTask.cs
@@ -57,15 +57,17 @@

         private static async Task RunTaskAsync()
         {
-            TileUpdateManager.CreateTileUpdaterForApplication().Clear();
-
             var scheduleItem =
                 await LiveTileAndLockScreenService.GetCurrentOrIncomingCourse();
-
+
             if (scheduleItem != null)
             {
                 UpdateTile(scheduleItem.ActivityName, scheduleItem.Location, scheduleItem.Name, scheduleItem.Group,
                     scheduleItem.StartDate, scheduleItem.EndDate);
+            }
+            else
+            {
+                TileUpdateManager.CreateTileUpdaterForApplication().Clear();
             }
         }


Organized WizardProjectLogic

Organized WizardProjectLogic


Remove debug output

Remove debug output

--- IPTables.Net/Iptables/Adapter/Client/IPTablesLibAdapterClient.cs
+++ IPTables.Net/Iptables/Adapter/Client/IPTablesLibAdapterClient.cs
@@ -158,7 +158,6 @@

         public override void DeleteChain(string table, string chainName, bool flush = false)
         {
-            Console.WriteLine("Delete Chain: "+ chainName);
             if (_inTransaction)
             {
                 GetInterface(table).DeleteChain(chainName);


Fixed possible division by zero

Fixed possible division by zero

--- SourceUtils.WebExport/Bsp/Geometry.cs
+++ SourceUtils.WebExport/Bsp/Geometry.cs
@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Linq;
 using Newtonsoft.Json;
 using OpenTK;
@@ -197,8 +198,19 @@
             _primitiveIndices.Clear();
         }

+        [Conditional("DEBUG")]
+        private static void AssertFinite( float value )
+        {
+            if ( float.IsNaN( value ) || float.IsInfinity( value ) )
+            {
+                throw new NotFiniteNumberException();
+            }
+        }
+
         public void VertexAttribute( VertexAttribute attrib, float value )
         {
+            AssertFinite( value );
+
             int offset;
             if ( !_attribOffsets.TryGetValue( attrib.Index, out offset ) ) return;
             _vertex[offset] = value;
@@ -206,6 +218,9 @@

         public void VertexAttribute(VertexAttribute attrib, Vector2 value)
         {
+            AssertFinite( value.X );
+            AssertFinite( value.Y );
+
             int offset;
             if (!_attribOffsets.TryGetValue(attrib.Index, out offset)) return;
             _vertex[offset + 0] = value.X;
@@ -214,6 +229,10 @@

         public void VertexAttribute(VertexAttribute attrib, SourceUtils.Vector3 value)
         {
+            AssertFinite( value.X );
+            AssertFinite( value.Y );
+            AssertFinite( value.Z );
+
             int offset;
             if (!_attribOffsets.TryGetValue(attrib.Index, out offset)) return;
             _vertex[offset + 0] = value.X;
@@ -517,7 +536,7 @@
                 meshData.Elements.Add(elem);
             }

-            var texScale = new Vector2(1f / texData.Width, 1f / texData.Height);
+            var texScale = new Vector2(1f / Math.Max(texData.Width, 1), 1f / Math.Max(texData.Height, 1));

             Vector2 lmMin, lmSize;
             bsp.LightmapLayout.GetUvs(faceIndex, out lmMin, out lmSize);


MC-4595: Fix exception 'No IUserTokenProvider is registered'

--- InfinniPlatform.Auth.Internal/IoC/AuthInternalContainerModule.cs
+++ InfinniPlatform.Auth.Internal/IoC/AuthInternalContainerModule.cs
@@ -11,6 +11,8 @@
 using InfinniPlatform.Sdk.Settings;

 using Microsoft.AspNet.Identity;
+using Microsoft.AspNet.Identity.Owin;
+using Microsoft.Owin.Security.DataProtection;

 namespace InfinniPlatform.Auth.Internal.IoC
 {
@@ -94,8 +96,14 @@
             // Сервис хэширования паролей пользователей для AspNet.Identity
             var identityPasswordHasher = new IdentityApplicationUserPasswordHasher(appPasswordHasher);

+            // Сервис генерации токенов безопасности для подтверждения действий
+            var dataProtectionProvider = new DpapiDataProtectionProvider("InfinniPlatform");
+            var dataProtector = dataProtectionProvider.Create("EmailConfirmation");
+            var tokenProvider = new DataProtectorTokenProvider<IdentityApplicationUser>(dataProtector);
+
             var userManager = new UserManager<IdentityApplicationUser>(identityUserStore)
                               {
+                                  UserTokenProvider = tokenProvider,
                                   UserValidator = identityUserValidator,
                                   PasswordHasher = identityPasswordHasher
                               };


Update Program.cs

Update Program.cs

--- LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs
+++ LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs
@@ -1,5 +1,4 @@
-using LanguageExt;
-using LogicPrograms.Interfaces;
+using LogicPrograms.Interfaces;
 using LogicPrograms.Logics;
 using System.Linq;
 using static System.Console;
@@ -13,7 +12,7 @@
             int[] array1 = { 1, 3, 5, 7, 9 };
             int min = 0, max = 0;

-            for(int index=0; index < array1.Length; index++)
+            for (int index = 0; index < array1.Length; index++)
             {
                 var current = array1.Sum() - array1[index];

@@ -23,7 +22,7 @@
                 }
                 else
                 {
-                    if(current > max)
+                    if (current > max)
                     {
                         max = current;
                     }
@@ -34,7 +33,7 @@
                 }
                 WriteLine(array1.Sum() - array1[index]);
             }
-            WriteLine($"{min} {max}");
+            WriteLine($"{min} {max}");

             GeneralPrograms generalPrograms = new GeneralPrograms();
             generalPrograms.DisplayStairCase(10);
@@ -94,3 +93,36 @@
     }

 }
+
+
+//static Int64 GetSum(int[] array1)
+//{
+//    Int64 sum = 0;
+//    for (var index = 0; index < array1.Length; index++)
+//    {
+//        sum += array1[index];
+//    }
+
+//    return sum;
+//}
+
+//static void miniMaxSum(int[] array1)
+//{
+//    Int64 sum = GetSum(array1);
+//    Int64 min = sum, max = 0;
+
+//    for (int index = 0; index < array1.Length; index++)
+//    {
+//        Int64 current = sum - array1[index];
+
+//        if (current > max)
+//        {
+//            max = current;
+//        }
+//        if (current < min)
+//        {
+//            min = current;
+//        }
+//    }
+//    Console.WriteLine($"{min} {max}");
+//}


[update]黒テーマへ対応

[update]黒テーマへ対応

--- Src/KIBOTTER/KIBOTTER/ScheduleForm.cs
+++ Src/KIBOTTER/KIBOTTER/ScheduleForm.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Drawing;
 using System.Windows.Forms;

 namespace KIBOTTER
@@ -50,6 +51,55 @@
                 TweetAccountComboBox.Items.Add(Form1Obj.AccountComboBox.Items[i]);
             }
             TweetAccountComboBox.SelectedIndex = 0;
+
+            if (Properties.Settings.Default.IsBlackTheme)
+                ChangeThemeToBlack();
+        }
+
+        private void ChangeThemeToBlack()
+        {
+            BackColor = Color.FromArgb(45, 45, 45);
+            DataGridView.EnableHeadersVisualStyles = false;
+            DataGridView.BackgroundColor = Color.FromArgb(45, 45, 45);
+            DataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(45, 45, 45);
+            DataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(45, 45, 45);
+            DataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
+            DataGridView.BorderStyle = BorderStyle.None;
+            DateColumn.DefaultCellStyle.BackColor = Color.FromArgb(62, 62, 62);
+            DateColumn.DefaultCellStyle.ForeColor = Color.White;
+            AccountColumn.DefaultCellStyle.BackColor = Color.FromArgb(62, 62, 62);
+            AccountColumn.DefaultCellStyle.ForeColor = Color.White;
+            ContentColumn.DefaultCellStyle.BackColor = Color.FromArgb(62, 62, 62);
+            ContentColumn.DefaultCellStyle.ForeColor = Color.White;
+            GroupBox.BackColor = Color.FromArgb(45, 45, 45);
+            GroupBox.ForeColor = Color.White;
+            GroupBox.FlatStyle = FlatStyle.Flat;
+            DateTimePicker.BackColor = Color.FromArgb(45, 45, 45);
+            DateTimePicker.ForeColor = Color.White;
+            DateTimePicker.CalendarForeColor = Color.White;
+            DateTimePicker.CalendarMonthBackground = Color.FromArgb(45, 45, 45);
+            DateTimePicker.CalendarTitleBackColor = Color.FromArgb(45, 45, 45);
+            DateTimePicker.CalendarTitleForeColor = Color.White;
+            DateTimePicker.CalendarTrailingForeColor = Color.FromArgb(100, 100, 100);
+            HourUpDown.BackColor = Color.FromArgb(45, 45, 45);
+            HourUpDown.ForeColor = Color.White;
+            MinuteUpDown.BackColor = Color.FromArgb(45, 45, 45);
+            MinuteUpDown.ForeColor = Color.White;
+            TweetAccountComboBox.DropDownStyle = ComboBoxStyle.DropDown;
+            TweetAccountComboBox.BackColor = Color.FromArgb(45, 45, 45);
+            TweetAccountComboBox.ForeColor = Color.White;
+            TweetAccountComboBox.FlatStyle = FlatStyle.Flat;
+            TweetAccountComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
+            ContentTextBox.BackColor = Color.FromArgb(62, 62, 62);
+            ContentTextBox.ForeColor = Color.White;
+            ScheduleButton.BackColor = Color.FromArgb(45, 45, 45);
+            ScheduleButton.ForeColor = Color.White;
+            ScheduleButton.FlatStyle = FlatStyle.Flat;
+        }
+
+        private void ChangeThemeToDefault()
+        {
+
         }

         private void ScheduleButton_Click(object sender, EventArgs e)


20000006-1142 #264 - Desenvolvimento da API que retorna os dados de algumas movimentações específicas do aluno.

--- Src/MSTech.GestaoEscolar.BLL/ApiBO.cs
+++ Src/MSTech.GestaoEscolar.BLL/ApiBO.cs
@@ -7512,7 +7512,20 @@
             {
                 DataTable dt = MTR_MovimentacaoBO.SelecionaMovimentacoesEspecificasPorAluno(filtros.ano, filtros.alu_id, filtros.mtu_id);

-
+                List<MovimentacaoDTO> lista = (from dr in dt.AsEnumerable()
+                                               orderby Convert.ToDateTime(dr["mov_dataRealizacao"]) descending
+                                               select new MovimentacaoDTO
+                                               {
+                                                    dataRealizacao = Convert.ToDateTime(dr["mov_dataRealizacao"]).ToString("dd/MM/yyyy")
+                                                    , tipo = dr["tmo_nome"].ToString()
+                                                    , escolaAnterior = dr["escolaAnterior"].ToString()
+                                                    , escolaAtual = dr["escolaAtual"].ToString()
+                                                    , turmaAnterior = dr["turmaAnterior"].ToString()
+                                                    , turmaAtual = dr["turmaAtual"].ToString()
+                                               }
+                                               ).ToList();
+
+                retorno.movimentacoes = lista;
             }
             catch (Exception ex)
             {


v1.2.0.3

v1.2.0.3

git-svn-id: c7824798988443d6e8397993074642516d192594@102 8d6e282c-8220-11de-b77e-d9b456c0130a

--- SuperPutty/Properties/AssemblyInfo.cs
+++ SuperPutty/Properties/AssemblyInfo.cs
@@ -32,5 +32,5 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.2.0.2")]
-[assembly: AssemblyFileVersion("1.2.0.2")]
+[assembly: AssemblyVersion("1.2.0.3")]
+[assembly: AssemblyFileVersion("1.2.0.3")]


add documentation

add documentation

--- OBeautifulCode.AccountingTime/Extensions/UnitOfTimeExtensions.cs
+++ OBeautifulCode.AccountingTime/Extensions/UnitOfTimeExtensions.cs
@@ -260,6 +260,7 @@
         /// <returns>
         /// The first calendar day in the specified calendar-based unit-of-time.
         /// </returns>
+        /// <exception cref="ArgumentNullException"><paramref name="unitOfTime"/> is null.</exception>
         public static CalendarDay GetFirstCalendarDay<T>(this T unitOfTime)
             where T : CalendarUnitOfTime
         {
@@ -303,6 +304,7 @@
         /// <returns>
         /// The last calendar day in the specified calendar-based unit-of-time.
         /// </returns>
+        /// <exception cref="ArgumentNullException"><paramref name="unitOfTime"/> is null.</exception>
         public static CalendarDay GetLastCalendarDay<T>(this T unitOfTime)
             where T : CalendarUnitOfTime
         {
@@ -348,6 +350,7 @@
         /// A list with the first <typeparamref name="T"/> in the same year as <paramref name="lastUnitOfTimeInYear"/>,
         /// up to and including <paramref name="lastUnitOfTimeInYear"/>, in sequential/ascending order.
         /// </returns>
+        /// <exception cref="ArgumentNullException"><paramref name="lastUnitOfTimeInYear"/> is null.</exception>
         public static IList<T> GetUnitsToDate<T>(this T lastUnitOfTimeInYear)
             where T : UnitOfTime, IHaveAYear
         {


Completed tests for PackageArchivesGetFqnVerification