diff --git a/src/Lithnet.Miiserver.AutoSync/ADListenerConfiguration.cs b/src/Lithnet.Miiserver.AutoSync/ADListenerConfiguration.cs index c884640..4d39bf1 100644 --- a/src/Lithnet.Miiserver.AutoSync/ADListenerConfiguration.cs +++ b/src/Lithnet.Miiserver.AutoSync/ADListenerConfiguration.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Net; namespace Lithnet.Miiserver.AutoSync @@ -37,22 +34,22 @@ internal void Validate() if (this.MinimumTriggerIntervalSeconds <= 0) { - throw new ArgumentOutOfRangeException("MinimumTriggerIntervalSeconds", "The MinimumTriggerIntervalSeconds parameter must be greater than 0"); + throw new ArgumentOutOfRangeException(nameof(this.MinimumTriggerIntervalSeconds), "The MinimumTriggerIntervalSeconds parameter must be greater than 0"); } if (string.IsNullOrWhiteSpace(this.BaseDN)) { - throw new ArgumentNullException("BaseDN", "A BaseDN must be specified"); + throw new ArgumentNullException(nameof(this.BaseDN), "A BaseDN must be specified"); } if (string.IsNullOrWhiteSpace(this.HostName)) { - throw new ArgumentNullException("HostName", "A host name must be specified"); + throw new ArgumentNullException(nameof(this.HostName), "A host name must be specified"); } if (this.ObjectClasses == null || this.ObjectClasses.Length == 0) { - throw new ArgumentNullException("ObjectClasses", "One or more object classes must be specified"); + throw new ArgumentNullException(nameof(this.ObjectClasses), "One or more object classes must be specified"); } } } diff --git a/src/Lithnet.Miiserver.AutoSync/AutoSyncService.cs b/src/Lithnet.Miiserver.AutoSync/AutoSyncService.cs index e0064c7..83495d3 100644 --- a/src/Lithnet.Miiserver.AutoSync/AutoSyncService.cs +++ b/src/Lithnet.Miiserver.AutoSync/AutoSyncService.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Diagnostics; -using System.Linq; -using System.ServiceProcess; -using System.Text; +using System.ServiceProcess; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/Enums/AutoImportScheduling.cs b/src/Lithnet.Miiserver.AutoSync/Enums/AutoImportScheduling.cs index e70f548..2659f61 100644 --- a/src/Lithnet.Miiserver.AutoSync/Enums/AutoImportScheduling.cs +++ b/src/Lithnet.Miiserver.AutoSync/Enums/AutoImportScheduling.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Lithnet.Miiserver.AutoSync +namespace Lithnet.Miiserver.AutoSync { public enum AutoImportScheduling { diff --git a/src/Lithnet.Miiserver.AutoSync/Enums/MARunProfileType.cs b/src/Lithnet.Miiserver.AutoSync/Enums/MARunProfileType.cs index 284db80..ac455b6 100644 --- a/src/Lithnet.Miiserver.AutoSync/Enums/MARunProfileType.cs +++ b/src/Lithnet.Miiserver.AutoSync/Enums/MARunProfileType.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Lithnet.Miiserver.AutoSync +namespace Lithnet.Miiserver.AutoSync { public enum MARunProfileType { diff --git a/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionParameters.cs b/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionParameters.cs index 1f117d2..ffdd242 100644 --- a/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionParameters.cs +++ b/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionParameters.cs @@ -1,13 +1,10 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Lithnet.Miiserver.AutoSync { public class ExecutionParameters { - public bool Exclusive { get; set; } + public bool Exclusive { get; set; } public string RunProfileName { get; set; } @@ -45,7 +42,7 @@ public override bool Equals(object obj) if (p2 == null) { - return base.Equals(obj); + return object.ReferenceEquals(this, obj); } return (string.Equals(this.RunProfileName, p2.RunProfileName, StringComparison.OrdinalIgnoreCase) && @@ -55,13 +52,15 @@ public override bool Equals(object obj) public override int GetHashCode() { - string hashcode = string.Format("{0}{1}{2}", this.RunProfileName, this.RunProfileType.ToString(), this.Exclusive.ToString()); + // ReSharper disable NonReadonlyMemberInGetHashCode + string hashcode = $"{this.RunProfileName}{this.RunProfileType}{this.Exclusive}"; + // ReSharper restore NonReadonlyMemberInGetHashCode return hashcode.GetHashCode(); } public static bool operator ==(ExecutionParameters a, ExecutionParameters b) { - if (Object.ReferenceEquals(a, b)) + if (object.ReferenceEquals(a, b)) { return true; } diff --git a/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionTriggerEventArgs.cs b/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionTriggerEventArgs.cs index dda3c4b..9c4d75c 100644 --- a/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionTriggerEventArgs.cs +++ b/src/Lithnet.Miiserver.AutoSync/EventArgs/ExecutionTriggerEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Lithnet.Miiserver.Client; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/EventArgs/SyncCompleteEventArgs.cs b/src/Lithnet.Miiserver.AutoSync/EventArgs/SyncCompleteEventArgs.cs index 009d343..89ebe7d 100644 --- a/src/Lithnet.Miiserver.AutoSync/EventArgs/SyncCompleteEventArgs.cs +++ b/src/Lithnet.Miiserver.AutoSync/EventArgs/SyncCompleteEventArgs.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/Global.cs b/src/Lithnet.Miiserver.AutoSync/Global.cs index 812dbb6..ed99c99 100644 --- a/src/Lithnet.Miiserver.AutoSync/Global.cs +++ b/src/Lithnet.Miiserver.AutoSync/Global.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Reflection; using System.IO; @@ -11,13 +8,6 @@ public static class Global { private static Random random = new Random(); - //static Global() - //{ - // Global.ScriptDirectory = Global.AssemblyDirectory; - //} - - //public static string ScriptDirectory { get; set; } - public static string AssemblyDirectory { get diff --git a/src/Lithnet.Miiserver.AutoSync/MAConfigDiscovery.cs b/src/Lithnet.Miiserver.AutoSync/MAConfigDiscovery.cs index 5d6a500..589c637 100644 --- a/src/Lithnet.Miiserver.AutoSync/MAConfigDiscovery.cs +++ b/src/Lithnet.Miiserver.AutoSync/MAConfigDiscovery.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; -using Lithnet.Miiserver.Client; using Lithnet.Logging; -using System.IO; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Host; -using System.Collections.ObjectModel; +using Lithnet.Miiserver.Client; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/MAConfigParameters.cs b/src/Lithnet.Miiserver.AutoSync/MAConfigParameters.cs index 1fe8186..accc18e 100644 --- a/src/Lithnet.Miiserver.AutoSync/MAConfigParameters.cs +++ b/src/Lithnet.Miiserver.AutoSync/MAConfigParameters.cs @@ -1,7 +1,5 @@ using System; using System.Collections; -using System.Linq; -using System.Text; namespace Lithnet.Miiserver.AutoSync { @@ -42,40 +40,22 @@ public MAConfigParameters(Hashtable config) this.ScheduledImportRunProfileName = config["ScheduledImportRunProfileName"] as string; this.DeltaImportRunProfileName = config["DeltaImportRunProfileName"] as string; this.ExportRunProfileName = config["ExportRunProfileName"] as string; - this.Disabled = config["Disabled"] == null ? false : Convert.ToBoolean(config["Disabled"]); + this.Disabled = config["Disabled"] != null && Convert.ToBoolean(config["Disabled"]); this.AutoImportScheduling = config["AutoImportScheduling"] == null ? AutoImportScheduling.Default : (AutoImportScheduling)Enum.Parse(typeof(AutoImportScheduling), config["AutoImportScheduling"].ToString(), true); - this.DisableDefaultTriggers = config["DisableDefaultTriggers"] == null ? false : Convert.ToBoolean(config["DisableDefaultTriggers"]); + this.DisableDefaultTriggers = config["DisableDefaultTriggers"] != null && Convert.ToBoolean(config["DisableDefaultTriggers"]); this.AutoImportIntervalMinutes = config["AutoImportIntervalMinutes"] == null ? 0 : Convert.ToInt32(config["AutoImportIntervalMinutes"]); } - internal bool CanExport - { - get - { - return this.ExportRunProfileName != null; - } - } + internal bool CanExport => this.ExportRunProfileName != null; - internal bool CanImport - { - get - { - return this.ScheduledImportRunProfileName != null || this.FullImportRunProfileName != null; - } - } + internal bool CanImport => this.ScheduledImportRunProfileName != null || this.FullImportRunProfileName != null; - internal bool CanAutoRun - { - get - { - return this.DeltaSyncRunProfileName != null || - this.ConfirmingImportRunProfileName != null || - this.FullSyncRunProfileName != null || - this.FullImportRunProfileName != null || - this.ScheduledImportRunProfileName != null || - this.ExportRunProfileName != null; - } - } + internal bool CanAutoRun => this.DeltaSyncRunProfileName != null || + this.ConfirmingImportRunProfileName != null || + this.FullSyncRunProfileName != null || + this.FullImportRunProfileName != null || + this.ScheduledImportRunProfileName != null || + this.ExportRunProfileName != null; internal string GetRunProfileName(MARunProfileType type) { @@ -95,7 +75,7 @@ internal string GetRunProfileName(MARunProfileType type) case MARunProfileType.FullSync: return this.FullSyncRunProfileName; - + default: case MARunProfileType.None: throw new ArgumentException("Unknown run profile type"); diff --git a/src/Lithnet.Miiserver.AutoSync/MAController.cs b/src/Lithnet.Miiserver.AutoSync/MAController.cs index 0fb27eb..4cd6978 100644 --- a/src/Lithnet.Miiserver.AutoSync/MAController.cs +++ b/src/Lithnet.Miiserver.AutoSync/MAController.cs @@ -1,15 +1,8 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.IO; using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Host; -using System.Threading.Tasks; -using System.Threading; using Lithnet.Logging; using Lithnet.Miiserver.Client; -using System.IO; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/MAExecutionTriggerDiscovery.cs b/src/Lithnet.Miiserver.AutoSync/MAExecutionTriggerDiscovery.cs index d77b912..8e00f25 100644 --- a/src/Lithnet.Miiserver.AutoSync/MAExecutionTriggerDiscovery.cs +++ b/src/Lithnet.Miiserver.AutoSync/MAExecutionTriggerDiscovery.cs @@ -1,14 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using Lithnet.Miiserver.Client; using Lithnet.Logging; using System.IO; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Host; -using System.Collections.ObjectModel; using System.Xml; namespace Lithnet.Miiserver.AutoSync @@ -142,22 +137,27 @@ private static IEnumerable GetDefaultTriggers(ManagementAge return triggers; } - if (ma.Category == "FIM") + switch (ma.Category) { - FimServicePendingImportTrigger t1 = new FimServicePendingImportTrigger(MAExecutionTriggerDiscovery.GetFimServiceHostName(ma)); - triggers.Add(t1); - } - else if (ma.Category == "AD") - { - ADListenerConfiguration listenerConfig = configItems.OfType().FirstOrDefault(); + case "FIM": + FimServicePendingImportTrigger t1 = new FimServicePendingImportTrigger(MAExecutionTriggerDiscovery.GetFimServiceHostName(ma)); + triggers.Add(t1); + break; - if (listenerConfig == null) - { - listenerConfig = GetADConfiguration(ma); - } + case "AD": + ADListenerConfiguration listenerConfig = configItems.OfType().FirstOrDefault(); - ActiveDirectoryChangeTrigger t2 = new ActiveDirectoryChangeTrigger(listenerConfig); - triggers.Add(t2); + if (listenerConfig == null) + { + listenerConfig = MAExecutionTriggerDiscovery.GetADConfiguration(ma); + } + + ActiveDirectoryChangeTrigger t2 = new ActiveDirectoryChangeTrigger(listenerConfig); + triggers.Add(t2); + break; + + default: + break; } return triggers; diff --git a/src/Lithnet.Miiserver.AutoSync/MAExecutor.cs b/src/Lithnet.Miiserver.AutoSync/MAExecutor.cs index da5c6ca..87e2282 100644 --- a/src/Lithnet.Miiserver.AutoSync/MAExecutor.cs +++ b/src/Lithnet.Miiserver.AutoSync/MAExecutor.cs @@ -1,42 +1,37 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; using System.Threading; using System.Collections.Concurrent; -using System.Diagnostics; using Lithnet.Miiserver.Client; -using Lithnet.ResourceManagement.Client; -using System.Xml; using Lithnet.Logging; -using System.Configuration; using System.Net.Mail; namespace Lithnet.Miiserver.AutoSync { public class MAExecutor { - protected static object globalStaggeredExecutionLock; - protected static ManualResetEvent globalExclusiveOperationLock; - protected static object globalSynchronizationStepLock; - protected static List allMaLocalOperationLocks; + protected static object GlobalStaggeredExecutionLock; + protected static ManualResetEvent GlobalExclusiveOperationLock; + protected static object GlobalSynchronizationStepLock; + protected static List AllMaLocalOperationLocks; public static event SyncCompleteEventHandler SyncComplete; public delegate void SyncCompleteEventHandler(object sender, SyncCompleteEventArgs e); private ManagementAgent ma; private BlockingCollection pendingActions; private ManualResetEvent localOperationLock; - private System.Timers.Timer ImportCheckTimer; - private System.Timers.Timer UnmanagedChangesCheckTimer; + private System.Timers.Timer importCheckTimer; + private System.Timers.Timer unmanagedChangesCheckTimer; private Dictionary perProfileLastRunStatus; - public MAConfigParameters Configuration { get; private set; } + public MAConfigParameters Configuration { get; } public string ExecutingRunProfile { get; private set; } - private List ExecutionTriggers { get; set; } + private List ExecutionTriggers { get; } private MAController controller; @@ -44,10 +39,10 @@ public class MAExecutor static MAExecutor() { - MAExecutor.globalSynchronizationStepLock = new object(); - MAExecutor.globalStaggeredExecutionLock = new object(); - MAExecutor.globalExclusiveOperationLock = new ManualResetEvent(true); - MAExecutor.allMaLocalOperationLocks = new List(); + MAExecutor.GlobalSynchronizationStepLock = new object(); + MAExecutor.GlobalStaggeredExecutionLock = new object(); + MAExecutor.GlobalExclusiveOperationLock = new ManualResetEvent(true); + MAExecutor.AllMaLocalOperationLocks = new List(); } public MAExecutor(ManagementAgent ma, MAConfigParameters profiles) @@ -60,7 +55,7 @@ public MAExecutor(ManagementAgent ma, MAConfigParameters profiles) this.token = new CancellationTokenSource(); this.controller = new MAController(ma); this.localOperationLock = new ManualResetEvent(true); - MAExecutor.allMaLocalOperationLocks.Add(this.localOperationLock); + MAExecutor.AllMaLocalOperationLocks.Add(this.localOperationLock); MAExecutor.SyncComplete += this.MAExecutor_SyncComplete; this.SetupImportSchedule(); this.SetupUnmanagedChangesCheckTimer(); @@ -68,11 +63,11 @@ public MAExecutor(ManagementAgent ma, MAConfigParameters profiles) private void SetupUnmanagedChangesCheckTimer() { - this.UnmanagedChangesCheckTimer = new System.Timers.Timer(); - this.UnmanagedChangesCheckTimer.Elapsed += this.UnmanagedChangesCheckTimer_Elapsed; - this.UnmanagedChangesCheckTimer.AutoReset = true; - this.UnmanagedChangesCheckTimer.Interval = Global.RandomizeOffset(Settings.UnmanagedChangesCheckInterval); - this.UnmanagedChangesCheckTimer.Start(); + this.unmanagedChangesCheckTimer = new System.Timers.Timer(); + this.unmanagedChangesCheckTimer.Elapsed += this.UnmanagedChangesCheckTimer_Elapsed; + this.unmanagedChangesCheckTimer.AutoReset = true; + this.unmanagedChangesCheckTimer.Interval = Global.RandomizeOffset(Settings.UnmanagedChangesCheckInterval); + this.unmanagedChangesCheckTimer.Start(); } private void UnmanagedChangesCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) @@ -87,13 +82,13 @@ private void SetupImportSchedule() if (this.Configuration.AutoImportScheduling == AutoImportScheduling.Enabled || (this.ma.ImportAttributeFlows.Select(t => t.ImportFlows).Count() >= this.ma.ExportAttributeFlows.Select(t => t.ExportFlows).Count())) { - this.ImportCheckTimer = new System.Timers.Timer(); - this.ImportCheckTimer.Elapsed += this.ImportCheckTimer_Elapsed; + this.importCheckTimer = new System.Timers.Timer(); + this.importCheckTimer.Elapsed += this.ImportCheckTimer_Elapsed; int importSeconds = this.Configuration.AutoImportIntervalMinutes > 0 ? this.Configuration.AutoImportIntervalMinutes * 60 : MAExecutionTriggerDiscovery.GetTriggerInterval(this.ma); - this.ImportCheckTimer.Interval = Global.RandomizeOffset(importSeconds * 1000); - this.ImportCheckTimer.AutoReset = true; + this.importCheckTimer.Interval = Global.RandomizeOffset(importSeconds * 1000); + this.importCheckTimer.AutoReset = true; Logger.WriteLine("{0}: Starting import interval timer. Imports will be queued if they have not been run for {1} seconds", this.ma.Name, importSeconds); - this.ImportCheckTimer.Start(); + this.importCheckTimer.Start(); } else { @@ -113,11 +108,11 @@ private void ImportCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventA private void ResetImportTimerOnImport() { - if (this.ImportCheckTimer != null) + if (this.importCheckTimer != null) { - Logger.WriteLine("{0}: Resetting import timer for {1} seconds", this.ma.Name, (int)(this.ImportCheckTimer.Interval / 1000)); - this.ImportCheckTimer.Stop(); - this.ImportCheckTimer.Start(); + Logger.WriteLine("{0}: Resetting import timer for {1} seconds", this.ma.Name, (int)(this.importCheckTimer.Interval / 1000)); + this.importCheckTimer.Stop(); + this.importCheckTimer.Start(); } } @@ -125,7 +120,7 @@ public void AttachTrigger(params IMAExecutionTrigger[] triggers) { if (triggers == null) { - throw new ArgumentNullException("triggers"); + throw new ArgumentNullException(nameof(triggers)); } foreach (IMAExecutionTrigger trigger in triggers) @@ -163,7 +158,7 @@ private void QueueFollowUpActionsExport(RunDetails d) { if (this.CanConfirmExport()) { - if (this.HasUnconfirmedExports(d)) + if (MAExecutor.HasUnconfirmedExports(d)) { this.AddPendingActionIfNotQueued(new ExecutionParameters(this.Configuration.ConfirmingImportRunProfileName), d.RunProfileName); } @@ -172,7 +167,7 @@ private void QueueFollowUpActionsExport(RunDetails d) private void QueueFollowUpActionsImport(RunDetails d) { - if (this.HasStagedImports(d)) + if (MAExecutor.HasStagedImports(d)) { this.AddPendingActionIfNotQueued(new ExecutionParameters(this.Configuration.DeltaSyncRunProfileName), d.RunProfileName); } @@ -189,19 +184,25 @@ private void QueueFollowUpActionsSync(RunDetails d) foreach (StepDetails s in d.StepDetails) { - if (s.StepDefinition.IsSyncStep) + if (!s.StepDefinition.IsSyncStep) { - foreach (var item in s.OutboundFlowCounters) - { - if (item.HasChanges) - { - SyncCompleteEventArgs args = new SyncCompleteEventArgs(); - args.SendingMAName = this.ma.Name; - args.TargetMA = item.MAID; + continue; + } - registeredHandlers(this, args); - } + foreach (OutboundFlowCounters item in s.OutboundFlowCounters) + { + if (!item.HasChanges) + { + continue; } + + SyncCompleteEventArgs args = new SyncCompleteEventArgs + { + SendingMAName = this.ma.Name, + TargetMA = item.MAID + }; + + registeredHandlers(this, args); } } } @@ -211,7 +212,7 @@ private void Execute(ExecutionParameters e) try { // Wait here if any exclusive operations are pending or in progress - MAExecutor.globalExclusiveOperationLock.WaitOne(); + MAExecutor.GlobalExclusiveOperationLock.WaitOne(); if (!this.controller.ShouldExecute(e.RunProfileName)) { @@ -226,11 +227,11 @@ private void Execute(ExecutionParameters e) Logger.WriteLine("{0}: Entering exclusive mode for {1}", this.ma.Name, e.RunProfileName); // Signal all executors to wait before running their next job - MAExecutor.globalExclusiveOperationLock.Reset(); + MAExecutor.GlobalExclusiveOperationLock.Reset(); // Wait for all MAs to finish their current job Logger.WriteLine("{0}: Waiting for running tasks to complete", this.ma.Name); - WaitHandle.WaitAll(MAExecutor.allMaLocalOperationLocks.ToArray()); + WaitHandle.WaitAll(MAExecutor.AllMaLocalOperationLocks.ToArray()); } // If another operation in this executor is already running, then wait for it to finish @@ -242,7 +243,7 @@ private void Execute(ExecutionParameters e) // Grab the staggered execution lock, and hold for x seconds // This ensures that no MA can start within x seconds of another MA // to avoid deadlock conditions - lock (MAExecutor.globalStaggeredExecutionLock) + lock (MAExecutor.GlobalStaggeredExecutionLock) { Thread.Sleep(Settings.ExecutionStaggerInterval * 1000); } @@ -276,9 +277,11 @@ private void Execute(ExecutionParameters e) } catch (System.Management.Automation.RuntimeException ex) { - if (ex.InnerException is UnexpectedChangeException) + UnexpectedChangeException changeException = ex.InnerException as UnexpectedChangeException; + + if (changeException != null) { - this.ProcessUnexpectedChangeException((UnexpectedChangeException)ex.InnerException); + this.ProcessUnexpectedChangeException(changeException); } else { @@ -303,7 +306,7 @@ private void Execute(ExecutionParameters e) if (e.Exclusive) { // Reset the global lock so pending operations can run - MAExecutor.globalExclusiveOperationLock.Set(); + MAExecutor.GlobalExclusiveOperationLock.Set(); } } } @@ -322,7 +325,7 @@ private void WaitOnUnmanagedRun() { Logger.WriteLine("{0}: Getting exclusive sync lock for unmanaged run", this.ma.Name); - lock (MAExecutor.globalSynchronizationStepLock) + lock (MAExecutor.GlobalSynchronizationStepLock) { this.ma.Wait(this.token.Token); } @@ -406,17 +409,11 @@ public Task Start() public void Stop() { - if (this.token != null) - { - this.token.Cancel(); - } + this.token?.Cancel(); - if (this.ImportCheckTimer != null) - { - this.ImportCheckTimer.Stop(); - } + this.importCheckTimer?.Stop(); - foreach (var x in this.ExecutionTriggers) + foreach (IMAExecutionTrigger x in this.ExecutionTriggers) { x.Stop(); } @@ -458,7 +455,7 @@ private void Init() if (this.ma.RunProfiles[action.RunProfileName].RunSteps.Any(t => t.IsSyncStep)) { - lock (MAExecutor.globalSynchronizationStepLock) + lock (MAExecutor.GlobalSynchronizationStepLock) { this.Execute(action); } @@ -499,28 +496,27 @@ private void CheckAndQueueUnmanagedChanges() private void MAExecutor_SyncComplete(object sender, SyncCompleteEventArgs e) { - if (e.TargetMA == this.ma.ID) + if (e.TargetMA != this.ma.ID) { - if (this.ShouldExport()) - { - ExecutionParameters p = new ExecutionParameters(this.Configuration.ExportRunProfileName); - this.AddPendingActionIfNotQueued(p, "Synchronization on " + e.SendingMAName); - } + return; } + + if (!this.ShouldExport()) + { + return; + } + + ExecutionParameters p = new ExecutionParameters(this.Configuration.ExportRunProfileName); + this.AddPendingActionIfNotQueued(p, "Synchronization on " + e.SendingMAName); } private void notifier_TriggerExecution(object sender, ExecutionTriggerEventArgs e) { IMAExecutionTrigger trigger = (IMAExecutionTrigger)sender; - string runProfile = e.Parameters.RunProfileName; if (string.IsNullOrWhiteSpace(e.Parameters.RunProfileName)) { - if (e.Parameters.RunProfileType != MARunProfileType.None) - { - runProfile = this.Configuration.GetRunProfileName(e.Parameters.RunProfileType); - } - else + if (e.Parameters.RunProfileType == MARunProfileType.None) { Logger.WriteLine("{0}: Received empty run profile from trigger {1}", this.ma.Name, trigger.Name); return; @@ -542,17 +538,21 @@ private void AddPendingActionIfNotQueued(ExecutionParameters p, string source) p.RunProfileName = this.Configuration.GetRunProfileName(p.RunProfileType); } - if (!this.pendingActions.Contains(p)) + if (this.pendingActions.Contains(p)) { - if (!p.RunProfileName.Equals(this.ExecutingRunProfile, StringComparison.OrdinalIgnoreCase)) - { - Logger.WriteLine("{0}: Queuing {1} (triggered by: {2})", this.ma.Name, p.RunProfileName, source); - this.pendingActions.Add(p); - } + return; } + + if (p.RunProfileName.Equals(this.ExecutingRunProfile, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + Logger.WriteLine("{0}: Queuing {1} (triggered by: {2})", this.ma.Name, p.RunProfileName, source); + this.pendingActions.Add(p); } - private bool HasUnconfirmedExports(RunDetails d) + private static bool HasUnconfirmedExports(RunDetails d) { if (d.StepDetails == null) { @@ -578,7 +578,7 @@ private bool HasUnconfirmedExports(RunDetails d) return false; } - private bool HasStagedImports(RunDetails d) + private static bool HasStagedImports(RunDetails d) { if (d.StepDetails == null) { @@ -604,14 +604,14 @@ private bool HasStagedImports(RunDetails d) return false; } - private bool HasUnconfirmedExports(StepDetails s) + private static bool HasUnconfirmedExports(StepDetails s) { return s?.ExportCounters?.HasChanges ?? false; } private bool HasUnconfirmedExportsInLastRun() { - return this.HasUnconfirmedExports(this.ma.GetLastRun()?.StepDetails?.FirstOrDefault()); + return MAExecutor.HasUnconfirmedExports(this.ma.GetLastRun()?.StepDetails?.FirstOrDefault()); } private bool ShouldExport() @@ -684,12 +684,7 @@ private static bool ShouldSendMail(RunDetails r) return false; } - if (Settings.MailIgnoreReturnCodes != null && Settings.MailIgnoreReturnCodes.Contains(r.LastStepStatus, StringComparer.OrdinalIgnoreCase)) - { - return false; - } - - return true; + return Settings.MailIgnoreReturnCodes == null || !Settings.MailIgnoreReturnCodes.Contains(r.LastStepStatus, StringComparer.OrdinalIgnoreCase); } private static bool CanSendMail() diff --git a/src/Lithnet.Miiserver.AutoSync/MessageBuilder.cs b/src/Lithnet.Miiserver.AutoSync/MessageBuilder.cs index 009670d..de626eb 100644 --- a/src/Lithnet.Miiserver.AutoSync/MessageBuilder.cs +++ b/src/Lithnet.Miiserver.AutoSync/MessageBuilder.cs @@ -2,30 +2,32 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using System.Diagnostics; -using Lithnet.Miiserver.Client; -using System.Xml; using System.Reflection; using System.IO; +using Lithnet.Miiserver.Client; using PreMailer.Net; namespace Lithnet.Miiserver.AutoSync { public static class MessageBuilder { - private const string simpleRow = "{0}{1}"; - // private const string cdataRow = "{0}"; - private const string firstRow = "{0}{1}{2}"; - private const string twoColumnHeader = "{1}{2}"; - private const string threeColumnHeader = "{1}{2}{3}"; + private const string SimpleRow = "{0}{1}"; + private const string FirstRow = "{0}{1}{2}"; + private const string TwoColumnHeader = "{1}{2}"; + private const string ThreeColumnHeader = "{1}{2}{3}"; private static string GetTemplate(string name) { Assembly assembly = Assembly.GetExecutingAssembly(); - string resourceName = string.Format("Lithnet.Miiserver.AutoSync.Resources.{0}.html", name); + string resourceName = $"Lithnet.Miiserver.AutoSync.Resources.{name}.html"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { + if (stream == null) + { + throw new InvalidOperationException($"The resource {resourceName} was missing from the assembly"); + } + using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); @@ -97,13 +99,13 @@ private static string BuildExportStepDetails(StepDetails d) { StringBuilder builder = new StringBuilder(); - string stepDetails = string.Format(twoColumnHeader, 6, d.StepNumber, d.StepDefinition.StepTypeDescription); - builder.AppendFormat(firstRow, stepDetails, "Export adds", d.ExportCounters.ExportAdd); - builder.AppendFormat(simpleRow, "Export deletes", d.ExportCounters.ExportDelete); - builder.AppendFormat(simpleRow, "Export delete-adds", d.ExportCounters.ExportDeleteAdd); - builder.AppendFormat(simpleRow, "Export rename", d.ExportCounters.ExportRename); - builder.AppendFormat(simpleRow, "Export update", d.ExportCounters.ExportUpdate); - builder.AppendFormat(simpleRow, "Export failures", d.ExportCounters.ExportFailure); + string stepDetails = string.Format(MessageBuilder.TwoColumnHeader, 6, d.StepNumber, d.StepDefinition.StepTypeDescription); + builder.AppendFormat(MessageBuilder.FirstRow, stepDetails, "Export adds", d.ExportCounters.ExportAdd); + builder.AppendFormat(MessageBuilder.SimpleRow, "Export deletes", d.ExportCounters.ExportDelete); + builder.AppendFormat(MessageBuilder.SimpleRow, "Export delete-adds", d.ExportCounters.ExportDeleteAdd); + builder.AppendFormat(MessageBuilder.SimpleRow, "Export rename", d.ExportCounters.ExportRename); + builder.AppendFormat(MessageBuilder.SimpleRow, "Export update", d.ExportCounters.ExportUpdate); + builder.AppendFormat(MessageBuilder.SimpleRow, "Export failures", d.ExportCounters.ExportFailure); return builder.ToString(); } @@ -112,14 +114,14 @@ private static string BuildImportStepDetails(StepDetails d) { StringBuilder builder = new StringBuilder(); - string stepDetails = string.Format(twoColumnHeader, 7, d.StepNumber, d.StepDefinition.StepTypeDescription); - builder.AppendFormat(firstRow, stepDetails, "Import adds", d.StagingCounters.StageAdd); - builder.AppendFormat(simpleRow, "Import deletes", d.StagingCounters.StageDelete); - builder.AppendFormat(simpleRow, "Import delete-adds", d.StagingCounters.StageDeleteAdd); - builder.AppendFormat(simpleRow, "Import rename", d.StagingCounters.StageRename); - builder.AppendFormat(simpleRow, "Import update", d.StagingCounters.StageUpdate); - builder.AppendFormat(simpleRow, "Import no change", d.StagingCounters.StageNoChange); - builder.AppendFormat(simpleRow, "Import failures", d.StagingCounters.StageFailure); + string stepDetails = string.Format(MessageBuilder.TwoColumnHeader, 7, d.StepNumber, d.StepDefinition.StepTypeDescription); + builder.AppendFormat(MessageBuilder.FirstRow, stepDetails, "Import adds", d.StagingCounters.StageAdd); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import deletes", d.StagingCounters.StageDelete); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import delete-adds", d.StagingCounters.StageDeleteAdd); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import rename", d.StagingCounters.StageRename); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import update", d.StagingCounters.StageUpdate); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import no change", d.StagingCounters.StageNoChange); + builder.AppendFormat(MessageBuilder.SimpleRow, "Import failures", d.StagingCounters.StageFailure); return builder.ToString(); } @@ -224,43 +226,43 @@ private static string BuildStagingErrorDetails(StepDetails d) { StringBuilder errorBuilder = new StringBuilder(); - errorBuilder.AppendFormat(simpleRow, "DN", error.DN); - errorBuilder.AppendFormat(simpleRow, "Error type", error.ErrorType); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "DN", error.DN); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error type", error.ErrorType); if (error.CDError != null) { - errorBuilder.AppendFormat(simpleRow, "Error code", error.CDError.ErrorCode); - errorBuilder.AppendFormat(simpleRow, "Error literal", error.CDError.ErrorLiteral); - errorBuilder.AppendFormat(simpleRow, "Server error detail", error.CDError.ServerErrorDetail); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error code", error.CDError.ErrorCode); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error literal", error.CDError.ErrorLiteral); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Server error detail", error.CDError.ServerErrorDetail); if (error.CDError.Value != null) { - errorBuilder.AppendFormat(simpleRow, "Value", error.CDError.Value.ToCommaSeparatedString()); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Value", error.CDError.Value.ToCommaSeparatedString()); } } if (error.LineNumber > 0) { - errorBuilder.AppendFormat(simpleRow, "Line number", error.LineNumber); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Line number", error.LineNumber); } if (error.ColumnNumber > 0) { - errorBuilder.AppendFormat(simpleRow, "Column number", error.ColumnNumber); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Column number", error.ColumnNumber); } if (error.AttributeName != null) { - errorBuilder.AppendFormat(simpleRow, "Attribute name", error.AttributeName); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Attribute name", error.AttributeName); } - errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder.ToString())); + errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder)); errorsBuilder.AppendLine("
"); } if (remainingErrors > 0) { - errorsBuilder.AppendFormat("There are {0} more errors that are not shown in this report
", remainingErrors); + errorsBuilder.Append($"There are {remainingErrors} more errors that are not shown in this report
"); } return errorsBuilder.ToString(); @@ -294,26 +296,26 @@ private static string BuildImportErrorDetails(StepDetails d) { StringBuilder errorBuilder = new StringBuilder(); - errorBuilder.AppendFormat(simpleRow, "DN", error.DN); - errorBuilder.AppendFormat(simpleRow, "Error type", error.ErrorType); - errorBuilder.AppendFormat(simpleRow, "Date occurred", error.DateOccurred.ToString()); - errorBuilder.AppendFormat(simpleRow, "Retry count", error.RetryCount); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "DN", error.DN); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error type", error.ErrorType); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Date occurred", error.DateOccurred); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Retry count", error.RetryCount); if (error.ExtensionErrorInfo != null) { - errorBuilder.AppendFormat(simpleRow, "Extension name", error.ExtensionErrorInfo.ExtensionName); - errorBuilder.AppendFormat(simpleRow, "Context", error.ExtensionErrorInfo.ExtensionContext); - errorBuilder.AppendFormat(simpleRow, "Call site", error.ExtensionErrorInfo.ExtensionCallSite.ToString()); - errorBuilder.AppendFormat(simpleRow, "Stack trace", error.ExtensionErrorInfo.CallStack); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Extension name", error.ExtensionErrorInfo.ExtensionName); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Context", error.ExtensionErrorInfo.ExtensionContext); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Call site", error.ExtensionErrorInfo.ExtensionCallSite); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Stack trace", error.ExtensionErrorInfo.CallStack); } - errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder.ToString())); + errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder)); errorsBuilder.AppendLine("
"); } if (remainingErrors > 0) { - errorsBuilder.AppendFormat("There are {0} more errors that are not shown in this report
", remainingErrors); + errorsBuilder.Append($"There are {remainingErrors} more errors that are not shown in this report
"); } return errorsBuilder.ToString(); @@ -347,27 +349,27 @@ private static string BuildExportErrorDetails(StepDetails d) { StringBuilder errorBuilder = new StringBuilder(); - errorBuilder.AppendFormat(simpleRow, "DN", error.DN); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "DN", error.DN); - errorBuilder.AppendFormat(simpleRow, "Error type", error.ErrorType); - errorBuilder.AppendFormat(simpleRow, "Date occurred", error.DateOccurred.ToString()); - errorBuilder.AppendFormat(simpleRow, "First occurred", error.FirstOccurred.ToString()); - errorBuilder.AppendFormat(simpleRow, "Retry count", error.RetryCount); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error type", error.ErrorType); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Date occurred", error.DateOccurred); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "First occurred", error.FirstOccurred); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Retry count", error.RetryCount); if (error.CDError != null) { - errorBuilder.AppendFormat(simpleRow, "Error code", error.CDError.ErrorCode); - errorBuilder.AppendFormat(simpleRow, "Error literal", error.CDError.ErrorLiteral); - errorBuilder.AppendFormat(simpleRow, "Server error detail", error.CDError.ServerErrorDetail); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error code", error.CDError.ErrorCode); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Error literal", error.CDError.ErrorLiteral); + errorBuilder.AppendFormat(MessageBuilder.SimpleRow, "Server error detail", error.CDError.ServerErrorDetail); } - errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder.ToString())); + errorsBuilder.AppendLine(string.Format(MessageBuilder.GetTemplate("ErrorTableFragment"), errorBuilder)); errorsBuilder.AppendLine("
"); } if (remainingErrors > 0) { - errorsBuilder.AppendFormat("There are {0} more errors that are not shown in this report
", remainingErrors); + errorsBuilder.Append($"There are {remainingErrors} more errors that are not shown in this report
"); } return errorsBuilder.ToString(); @@ -377,26 +379,26 @@ private static string BuildSyncStepDetails(StepDetails d) { StringBuilder builder = new StringBuilder(); - string stepDetails = string.Format(threeColumnHeader, 10, d.StepNumber, d.StepDefinition.StepTypeDescription, "Inbound"); - builder.AppendFormat(firstRow, stepDetails, "Projections", d.InboundFlowCounters.TotalProjections); - builder.AppendFormat(simpleRow, "Joins", d.InboundFlowCounters.TotalJoins); - builder.AppendFormat(simpleRow, "Filtered disconnectors", d.InboundFlowCounters.DisconnectorFiltered); - builder.AppendFormat(simpleRow, "Disconnectors", d.InboundFlowCounters.DisconnectedRemains); - builder.AppendFormat(simpleRow, "Connectors with flow updates", d.InboundFlowCounters.ConnectorFlow); - builder.AppendFormat(simpleRow, "Connectors without flow updates", d.InboundFlowCounters.ConnectorNoFlow); - builder.AppendFormat(simpleRow, "Filtered connectors", d.InboundFlowCounters.TotalFilteredConnectors); - builder.AppendFormat(simpleRow, "Deleted connectors", d.InboundFlowCounters.TotalDeletedConnectors); - builder.AppendFormat(simpleRow, "Metaverse object deletes", d.InboundFlowCounters.TotalMVObjectDeletes); - builder.AppendFormat(simpleRow, "Flow errors", d.InboundFlowCounters.FlowFailure); + string stepDetails = string.Format(MessageBuilder.ThreeColumnHeader, 10, d.StepNumber, d.StepDefinition.StepTypeDescription, "Inbound"); + builder.AppendFormat(MessageBuilder.FirstRow, stepDetails, "Projections", d.InboundFlowCounters.TotalProjections); + builder.AppendFormat(MessageBuilder.SimpleRow, "Joins", d.InboundFlowCounters.TotalJoins); + builder.AppendFormat(MessageBuilder.SimpleRow, "Filtered disconnectors", d.InboundFlowCounters.DisconnectorFiltered); + builder.AppendFormat(MessageBuilder.SimpleRow, "Disconnectors", d.InboundFlowCounters.DisconnectedRemains); + builder.AppendFormat(MessageBuilder.SimpleRow, "Connectors with flow updates", d.InboundFlowCounters.ConnectorFlow); + builder.AppendFormat(MessageBuilder.SimpleRow, "Connectors without flow updates", d.InboundFlowCounters.ConnectorNoFlow); + builder.AppendFormat(MessageBuilder.SimpleRow, "Filtered connectors", d.InboundFlowCounters.TotalFilteredConnectors); + builder.AppendFormat(MessageBuilder.SimpleRow, "Deleted connectors", d.InboundFlowCounters.TotalDeletedConnectors); + builder.AppendFormat(MessageBuilder.SimpleRow, "Metaverse object deletes", d.InboundFlowCounters.TotalMVObjectDeletes); + builder.AppendFormat(MessageBuilder.SimpleRow, "Flow errors", d.InboundFlowCounters.FlowFailure); foreach (OutboundFlowCounters item in d.OutboundFlowCounters) { - string f = string.Format(threeColumnHeader, 5, string.Empty, string.Empty, "Outbound: " + item.ManagementAgent); - builder.AppendFormat(firstRow, f, "Export attribute flow", item.ConnectorFlow); - builder.AppendFormat(simpleRow, "Provisioning adds", (item.ProvisionedAddFlow + item.ProvisionedAddNoFlow)); - builder.AppendFormat(simpleRow, "Provisioning renames", (item.ProvisionRenameFlow + item.ProvisionedRenameNoFlow)); - builder.AppendFormat(simpleRow, "Provisioning disconnects", item.ProvisionedDisconnect); - builder.AppendFormat(simpleRow, "Provisioning delete-adds", (item.ProvisionedDeleteAddFlow + item.ProvisionedDeleteAddNoFlow)); + string f = string.Format(MessageBuilder.ThreeColumnHeader, 5, string.Empty, string.Empty, "Outbound: " + item.ManagementAgent); + builder.AppendFormat(MessageBuilder.FirstRow, f, "Export attribute flow", item.ConnectorFlow); + builder.AppendFormat(MessageBuilder.SimpleRow, "Provisioning adds", (item.ProvisionedAddFlow + item.ProvisionedAddNoFlow)); + builder.AppendFormat(MessageBuilder.SimpleRow, "Provisioning renames", (item.ProvisionRenameFlow + item.ProvisionedRenameNoFlow)); + builder.AppendFormat(MessageBuilder.SimpleRow, "Provisioning disconnects", item.ProvisionedDisconnect); + builder.AppendFormat(MessageBuilder.SimpleRow, "Provisioning delete-adds", (item.ProvisionedDeleteAddFlow + item.ProvisionedDeleteAddNoFlow)); } diff --git a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/CallBackEventBridge.cs b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/CallBackEventBridge.cs index ff5daf8..2a0bbd0 100644 --- a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/CallBackEventBridge.cs +++ b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/CallBackEventBridge.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Lithnet.Miiserver.AutoSync { @@ -18,13 +15,7 @@ private void CallbackInternal(IAsyncResult result) this.CallbackComplete(result); } - public AsyncCallback Callback - { - get - { - return new AsyncCallback(this.CallbackInternal); - } - } + public AsyncCallback Callback => this.CallbackInternal; public static CallbackEventBridge Create() { diff --git a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchChangeType.cs b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchChangeType.cs index e8e6795..7ff19cc 100644 --- a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchChangeType.cs +++ b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchChangeType.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchControl.cs b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchControl.cs index 7210620..4656198 100644 --- a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchControl.cs +++ b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchControl.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.DirectoryServices.Protocols; +using System.DirectoryServices.Protocols; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchOptions.cs b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchOptions.cs index 3c14f9d..43e7700 100644 --- a/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchOptions.cs +++ b/src/Lithnet.Miiserver.AutoSync/PersistentSearch/PersistentSearchOptions.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.DirectoryServices.Protocols; +using System.DirectoryServices.Protocols; namespace Lithnet.Miiserver.AutoSync { diff --git a/src/Lithnet.Miiserver.AutoSync/Program.cs b/src/Lithnet.Miiserver.AutoSync/Program.cs index 72da3a8..4f739bf 100644 --- a/src/Lithnet.Miiserver.AutoSync/Program.cs +++ b/src/Lithnet.Miiserver.AutoSync/Program.cs @@ -12,8 +12,6 @@ namespace Lithnet.Miiserver.AutoSync { - using System.Security.Principal; - public static class Program { private static List maExecutors = new List(); @@ -115,7 +113,7 @@ private static void ClearRunHistory() if (Settings.SaveRunHistory && Settings.RunHistorySavePath != null) { - string file = Path.Combine(Settings.RunHistorySavePath, string.Format("history-{0}.xml", DateTime.Now.ToString("yyyy-MM-ddThh.mm.ss"))); + string file = Path.Combine(Settings.RunHistorySavePath, $"history-{DateTime.Now.ToString("yyyy-MM-ddThh.mm.ss")}.xml"); SyncServer.ClearRunHistory(clearBeforeDate, file); } else diff --git a/src/Lithnet.Miiserver.AutoSync/Settings.cs b/src/Lithnet.Miiserver.AutoSync/Settings.cs index 8b54afc..c276c27 100644 --- a/src/Lithnet.Miiserver.AutoSync/Settings.cs +++ b/src/Lithnet.Miiserver.AutoSync/Settings.cs @@ -1,16 +1,11 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; +using System.Reflection; using System.Configuration; +using Microsoft.Win32; namespace Lithnet.Miiserver.AutoSync { - using System.IO; - using System.Reflection; - using Microsoft.Win32; - internal static class Settings { private static RegistryKey key; @@ -43,7 +38,8 @@ public static string LogFile UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); string dirName = Path.GetDirectoryName(path); - return Path.Combine(dirName, "Logs\\autosync.log"); + + return Path.Combine(dirName ?? Global.AssemblyDirectory, "Logs\\autosync.log"); } } @@ -62,7 +58,7 @@ public static int MailMaxErrorItems { string s = Settings.BaseKey.GetValue("MailMaxErrors") as string; - int value = 0; + int value; return int.TryParse(s, out value) ? value : 0; } @@ -74,7 +70,7 @@ public static int RunHistoryNumberOfDaysToKeep { string s = Settings.BaseKey.GetValue("RunHistoryAge") as string; - int value = 0; + int value; return int.TryParse(s, out value) ? value : 0; } @@ -105,7 +101,7 @@ public static int UnmanagedChangesCheckInterval { string s = Settings.BaseKey.GetValue("UnmanagedChangesCheckIntervalMinutes") as string; - int value = 0; + int value; if (int.TryParse(s, out value)) { @@ -128,7 +124,7 @@ public static int MailServerPort { string s = Settings.BaseKey.GetValue("MailServerPort") as string; - int value = 0; + int value; if (int.TryParse(s, out value)) { diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/ActiveDirectoryChangeTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/ActiveDirectoryChangeTrigger.cs index 921a530..93a7449 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/ActiveDirectoryChangeTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/ActiveDirectoryChangeTrigger.cs @@ -1,31 +1,28 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Timers; -using Lithnet.ResourceManagement.Client; using Lithnet.Logging; using System.DirectoryServices.Protocols; -using System.Xml; namespace Lithnet.Miiserver.AutoSync { public class ActiveDirectoryChangeTrigger : IMAExecutionTrigger { - private const string lastLogonAttributeName = "lastLogon"; - private const string lastLogonTimeStampAttributeName = "lastLogonTimeStamp"; - private const string badPasswordAttribute = "badPasswordTime"; - private const string objectClassAttribute = "objectClass"; + private const string LastLogonAttributeName = "lastLogon"; + private const string LastLogonTimeStampAttributeName = "lastLogonTimeStamp"; + private const string BadPasswordAttribute = "badPasswordTime"; + private const string ObjectClassAttribute = "objectClass"; - private int LastLogonTimestampOffset; + private int lastLogonTimestampOffset; public event ExecutionTriggerEventHandler TriggerExecution; - public Timer checkTimer; + private Timer checkTimer; private ADListenerConfiguration config; - private bool hasChanges = false; + private bool hasChanges; private LdapConnection connection; @@ -33,7 +30,7 @@ public class ActiveDirectoryChangeTrigger : IMAExecutionTrigger public ActiveDirectoryChangeTrigger(ADListenerConfiguration config) { - this.LastLogonTimestampOffset = config.LastLogonTimestampOffsetSeconds; + this.lastLogonTimestampOffset = config.LastLogonTimestampOffsetSeconds; config.Validate(); this.config = config; } @@ -71,12 +68,14 @@ private void SetupListener() this.config.BaseDN, "(objectClass=*)", SearchScope.Subtree, - new string[] { objectClassAttribute, lastLogonAttributeName, lastLogonTimeStampAttributeName, badPasswordAttribute } - ); + ActiveDirectoryChangeTrigger.ObjectClassAttribute, + ActiveDirectoryChangeTrigger.LastLogonAttributeName, + ActiveDirectoryChangeTrigger.LastLogonTimeStampAttributeName, + ActiveDirectoryChangeTrigger.BadPasswordAttribute); request.Controls.Add(new DirectoryNotificationControl()); - IAsyncResult result = this.connection.BeginSendRequest( + this.connection.BeginSendRequest( request, TimeSpan.FromDays(100), PartialResultProcessing.ReturnPartialResultsAndNotifyCallback, this.Notify, @@ -100,67 +99,69 @@ private void Notify(IAsyncResult result) return; } - DateTime lastLogonOldestDate = DateTime.UtcNow.AddSeconds(-this.LastLogonTimestampOffset); + DateTime lastLogonOldestDate = DateTime.UtcNow.AddSeconds(-this.lastLogonTimestampOffset); foreach (SearchResultEntry r in col.OfType()) { - IEnumerable objectClasses = r.Attributes[objectClassAttribute].GetValues(typeof(string)).OfType(); + IList objectClasses = r.Attributes[ActiveDirectoryChangeTrigger.ObjectClassAttribute].GetValues(typeof(string)).OfType().ToList(); - if (this.config.ObjectClasses.Intersect(objectClasses, StringComparer.OrdinalIgnoreCase).Any()) + if (!this.config.ObjectClasses.Intersect(objectClasses, StringComparer.OrdinalIgnoreCase).Any()) { - if (objectClasses.Contains("computer", StringComparer.OrdinalIgnoreCase) && !this.config.ObjectClasses.Contains("computer", StringComparer.OrdinalIgnoreCase)) - { - continue; - } + continue; + } - DateTime date1 = DateTime.MinValue; + if (objectClasses.Contains("computer", StringComparer.OrdinalIgnoreCase) && !this.config.ObjectClasses.Contains("computer", StringComparer.OrdinalIgnoreCase)) + { + continue; + } - if (r.Attributes.Contains(lastLogonAttributeName)) - { - string ts = r.Attributes[lastLogonAttributeName][0] as string; - date1 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); + DateTime date1 = DateTime.MinValue; - if (date1 > lastLogonOldestDate) - { - continue; - } + if (r.Attributes.Contains(ActiveDirectoryChangeTrigger.LastLogonAttributeName)) + { + string ts = r.Attributes[ActiveDirectoryChangeTrigger.LastLogonAttributeName][0] as string; + date1 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); + + if (date1 > lastLogonOldestDate) + { + continue; } + } - DateTime date2 = DateTime.MinValue; + DateTime date2 = DateTime.MinValue; - if (r.Attributes.Contains(lastLogonTimeStampAttributeName)) - { - string ts = r.Attributes[lastLogonTimeStampAttributeName][0] as string; - date2 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); + if (r.Attributes.Contains(ActiveDirectoryChangeTrigger.LastLogonTimeStampAttributeName)) + { + string ts = r.Attributes[ActiveDirectoryChangeTrigger.LastLogonTimeStampAttributeName][0] as string; + date2 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); - if (date2 > lastLogonOldestDate) - { - continue; - } + if (date2 > lastLogonOldestDate) + { + continue; } + } - DateTime date3 = DateTime.MinValue; + DateTime date3 = DateTime.MinValue; - if (r.Attributes.Contains(badPasswordAttribute)) - { - string ts = r.Attributes[badPasswordAttribute][0] as string; - date3 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); + if (r.Attributes.Contains(ActiveDirectoryChangeTrigger.BadPasswordAttribute)) + { + string ts = r.Attributes[ActiveDirectoryChangeTrigger.BadPasswordAttribute][0] as string; + date3 = DateTime.FromFileTimeUtc(Convert.ToInt64(ts)); - if (date3 > lastLogonOldestDate) - { - continue; - } + if (date3 > lastLogonOldestDate) + { + continue; } + } - Logger.WriteLine("AD change: {0}", r.DistinguishedName); - Logger.WriteLine("LL: {0}", LogLevel.Debug, date1.ToLocalTime()); - Logger.WriteLine("TS: {0}", LogLevel.Debug, date2.ToLocalTime()); - Logger.WriteLine("BP: {0}", LogLevel.Debug, date3.ToLocalTime()); + Logger.WriteLine("AD change: {0}", r.DistinguishedName); + Logger.WriteLine("LL: {0}", LogLevel.Debug, date1.ToLocalTime()); + Logger.WriteLine("TS: {0}", LogLevel.Debug, date2.ToLocalTime()); + Logger.WriteLine("BP: {0}", LogLevel.Debug, date3.ToLocalTime()); - this.hasChanges = true; - return; - } + this.hasChanges = true; + return; } } catch (LdapException ex) @@ -201,8 +202,12 @@ public void Start() Logger.EndThreadLog(); } this.SetupListener(); - this.checkTimer = new Timer(minimumTriggerInterval * 1000); - this.checkTimer.AutoReset = true; + this.checkTimer = new Timer + { + AutoReset = true, + Interval = minimumTriggerInterval * 1000 + }; + this.checkTimer.Elapsed += this.checkTimer_Elapsed; this.checkTimer.Start(); } diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/FimServicePendingImportTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/FimServicePendingImportTrigger.cs index bbf4f61..a94f966 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/FimServicePendingImportTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/FimServicePendingImportTrigger.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Timers; using Lithnet.ResourceManagement.Client; using Lithnet.Logging; @@ -10,9 +8,9 @@ namespace Lithnet.Miiserver.AutoSync { public class FimServicePendingImportTrigger : IMAExecutionTrigger { - public Timer checkTimer; + private Timer checkTimer; - public int TimerIntervalSeconds { get; set; } + private int TimerIntervalSeconds { get; } private DateTime? lastCheckDateTime; @@ -43,21 +41,20 @@ private void checkTimer_Elapsed(object sender, ElapsedEventArgs e) Logger.WriteLine("Searching for changes since {0}", LogLevel.Debug, this.lastCheckDateTime.Value.ToResourceManagementServiceDateFormat(false)); } - ISearchResultCollection r = c.GetResources(xpath, 1, new string[] { "msidmCompletedTime" }, "msidmCompletedTime", false); + ISearchResultCollection r = c.GetResources(xpath, 1, new[] { "msidmCompletedTime" }, "msidmCompletedTime", false); Logger.WriteLine("Found {0} change{1}", LogLevel.Debug, r.Count, r.Count == 1 ? string.Empty : "s"); - if (r.Count > 0) + if (r.Count <= 0) { - this.lastCheckDateTime = r.First().Attributes["msidmCompletedTime"].DateTimeValue; + return; + } - ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; + this.lastCheckDateTime = r.First().Attributes["msidmCompletedTime"].DateTimeValue; - if (registeredHandlers != null) - { - registeredHandlers(this, new ExecutionTriggerEventArgs(MARunProfileType.DeltaImport)); - } - } + ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; + + registeredHandlers?.Invoke(this, new ExecutionTriggerEventArgs(MARunProfileType.DeltaImport)); } catch (Exception ex) { @@ -68,31 +65,31 @@ private void checkTimer_Elapsed(object sender, ElapsedEventArgs e) public void Start() { - this.checkTimer = new Timer(this.TimerIntervalSeconds * 1000); - this.checkTimer.AutoReset = true; + this.checkTimer = new Timer + { + AutoReset = true, + Interval = this.TimerIntervalSeconds*1000 + }; + this.checkTimer.Elapsed += this.checkTimer_Elapsed; this.checkTimer.Start(); } public void Stop() { - if (this.checkTimer != null) + if (this.checkTimer == null) { - if (this.checkTimer.Enabled) - { - this.checkTimer.Stop(); - } + return; } - } - public string Name - { - get + if (this.checkTimer.Enabled) { - return "FIM Service pending changes"; + this.checkTimer.Stop(); } } + public string Name => "FIM Service pending changes"; + public event ExecutionTriggerEventHandler TriggerExecution; } } \ No newline at end of file diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/IMAExecutionTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/IMAExecutionTrigger.cs index 3c35fd7..f8c6de6 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/IMAExecutionTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/IMAExecutionTrigger.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Lithnet.Miiserver.AutoSync +namespace Lithnet.Miiserver.AutoSync { public delegate void ExecutionTriggerEventHandler(object sender, ExecutionTriggerEventArgs e); diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/IntervalExecutionTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/IntervalExecutionTrigger.cs index 2843c89..f204cfe 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/IntervalExecutionTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/IntervalExecutionTrigger.cs @@ -1,19 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Timers; -using Lithnet.ResourceManagement.Client; +using System.Timers; using Lithnet.Logging; namespace Lithnet.Miiserver.AutoSync { public class IntervalExecutionTrigger : IMAExecutionTrigger { - public Timer checkTimer; + private Timer checkTimer; + + private int TriggerInterval { get; } - public int TriggerInterval { get; set; } - public MARunProfileType RunProfileTargetType { get; set; } public IntervalExecutionTrigger(MARunProfileType type, int intervalSeconds) @@ -26,42 +21,38 @@ private void checkTimer_Elapsed(object sender, ElapsedEventArgs e) { ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; - if (registeredHandlers != null) - { - registeredHandlers(this, new ExecutionTriggerEventArgs(this.RunProfileTargetType)); - } + registeredHandlers?.Invoke(this, new ExecutionTriggerEventArgs(this.RunProfileTargetType)); } public void Start() { Logger.WriteLine("Starting interval timer for {0} at {1} seconds", LogLevel.Debug, this.RunProfileTargetType, this.TriggerInterval); - this.checkTimer = new Timer(this.TriggerInterval * 1000); + this.checkTimer = new Timer + { + Interval = this.TriggerInterval * 1000, + AutoReset = true + }; - this.checkTimer.AutoReset = true; this.checkTimer.Elapsed += this.checkTimer_Elapsed; this.checkTimer.Start(); } public void Stop() { - if (this.checkTimer != null) + if (this.checkTimer == null) { - if (this.checkTimer.Enabled) - { - this.checkTimer.Stop(); - } + return; } - } - public string Name - { - get + if (this.checkTimer.Enabled) { - return string.Format("{0} second interval", this.TriggerInterval); + this.checkTimer.Stop(); } } + public string Name => $"{this.TriggerInterval} second interval"; + public event ExecutionTriggerEventHandler TriggerExecution; } } diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/PowerShellExecutionTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/PowerShellExecutionTrigger.cs index b88ebb6..81361fe 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/PowerShellExecutionTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/PowerShellExecutionTrigger.cs @@ -1,10 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Host; using System.Threading.Tasks; using System.Threading; using Lithnet.Logging; @@ -17,13 +12,7 @@ public class PowerShellExecutionTrigger : IMAExecutionTrigger public string ScriptPath { get; set; } - public string Name - { - get - { - return System.IO.Path.GetFileName(this.ScriptPath); - } - } + public string Name => System.IO.Path.GetFileName(this.ScriptPath); public event ExecutionTriggerEventHandler TriggerExecution; @@ -59,11 +48,12 @@ public void Start() ExecutionParameters p = result.BaseObject as ExecutionParameters; - if (p != null) + if (p == null) { - this.Fire(p); continue; } + + this.Fire(p); } Thread.Sleep(5000); @@ -88,20 +78,14 @@ public void Fire(string runProfileName) { ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; - if (registeredHandlers != null) - { - registeredHandlers(this, new ExecutionTriggerEventArgs(runProfileName)); - } + registeredHandlers?.Invoke(this, new ExecutionTriggerEventArgs(runProfileName)); } public void Fire(ExecutionParameters p) { ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; - if (registeredHandlers != null) - { - registeredHandlers(this, new ExecutionTriggerEventArgs(p)); - } + registeredHandlers?.Invoke(this, new ExecutionTriggerEventArgs(p)); } } } diff --git a/src/Lithnet.Miiserver.AutoSync/Triggers/ScheduledExecutionTrigger.cs b/src/Lithnet.Miiserver.AutoSync/Triggers/ScheduledExecutionTrigger.cs index 06e7f67..5cd97be 100644 --- a/src/Lithnet.Miiserver.AutoSync/Triggers/ScheduledExecutionTrigger.cs +++ b/src/Lithnet.Miiserver.AutoSync/Triggers/ScheduledExecutionTrigger.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Timers; using Lithnet.Logging; @@ -9,7 +6,7 @@ namespace Lithnet.Miiserver.AutoSync { public class ScheduledExecutionTrigger : IMAExecutionTrigger { - public Timer checkTimer; + private Timer checkTimer; public DateTime StartDateTime { get; set; } @@ -17,7 +14,7 @@ public class ScheduledExecutionTrigger : IMAExecutionTrigger public string RunProfileName { get; set; } - private double remainingMiliseconds { get; set; } + private double RemainingMiliseconds { get; set; } public ScheduledExecutionTrigger() { @@ -25,7 +22,7 @@ public ScheduledExecutionTrigger() private void SetRemainingMiliseconds() { - if (this.Interval.TotalSeconds == 0) + if (this.Interval.TotalSeconds < 1) { throw new ArgumentException("The interval cannot be zero"); } @@ -44,17 +41,14 @@ private void SetRemainingMiliseconds() } Logger.WriteLine("Scheduling event for " + triggerTime, LogLevel.Debug); - this.remainingMiliseconds = (triggerTime - now).TotalMilliseconds; + this.RemainingMiliseconds = (triggerTime - now).TotalMilliseconds; } private void checkTimer_Elapsed(object sender, ElapsedEventArgs e) { ExecutionTriggerEventHandler registeredHandlers = this.TriggerExecution; - if (registeredHandlers != null) - { - registeredHandlers(this, new ExecutionTriggerEventArgs(this.RunProfileName)); - } + registeredHandlers?.Invoke(this, new ExecutionTriggerEventArgs(this.RunProfileName)); this.Start(); } @@ -62,32 +56,31 @@ private void checkTimer_Elapsed(object sender, ElapsedEventArgs e) public void Start() { this.SetRemainingMiliseconds(); - this.checkTimer = new Timer(this.remainingMiliseconds); + this.checkTimer = new Timer + { + Interval = this.RemainingMiliseconds, + AutoReset = false + }; - this.checkTimer.AutoReset = false; this.checkTimer.Elapsed += this.checkTimer_Elapsed; this.checkTimer.Start(); } public void Stop() { - if (this.checkTimer != null) + if (this.checkTimer == null) { - if (this.checkTimer.Enabled) - { - this.checkTimer.Stop(); - } + return; } - } - public string Name - { - get + if (this.checkTimer.Enabled) { - return "Scheduled trigger"; + this.checkTimer.Stop(); } } + public string Name => "Scheduled trigger"; + public event ExecutionTriggerEventHandler TriggerExecution; } } diff --git a/src/Lithnet.Miiserver.AutoSync/UnexpectedChangeException.cs b/src/Lithnet.Miiserver.AutoSync/UnexpectedChangeException.cs index f61d7db..0420892 100644 --- a/src/Lithnet.Miiserver.AutoSync/UnexpectedChangeException.cs +++ b/src/Lithnet.Miiserver.AutoSync/UnexpectedChangeException.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Lithnet.Miiserver.AutoSync { @@ -11,12 +7,10 @@ public class UnexpectedChangeException : Exception public bool ShouldTerminateService { get; set; } public UnexpectedChangeException() - : base() { } public UnexpectedChangeException(bool shouldTerminateService) - : base() { this.ShouldTerminateService = shouldTerminateService; }