protected NTPInformation GetNTP() { NTPInformation ntpInformation = null; RunStep(() => { ntpInformation = Client.GetNTP(); }, "Get NTP information"); return(ntpInformation); }
/// <summary> /// Checks if NTP information is valid. /// </summary> /// <param name="ntpInformation">NTP information.</param> /// <param name="ipAddressesMandatory">True, if IP address cannot be omitted.</param> /// <param name="reason">Failure reason.</param> /// <returns></returns> public static bool IsValidNTPInformation(this NTPInformation ntpInformation, bool ipAddressesMandatory, out string reason) { reason = string.Empty; if (ntpInformation.FromDHCP) { if ((ntpInformation.NTPManual != null) && (ntpInformation.NTPManual.Length > 0)) { reason = "NTPManual is not empty, while FromDHCP is true"; return(false); } if ((ntpInformation.NTPFromDHCP != null) && !AreValidHosts(ntpInformation.NTPFromDHCP, ipAddressesMandatory, out reason)) { return(false); } } else { if ((ntpInformation.NTPFromDHCP != null) && (ntpInformation.NTPFromDHCP.Length > 0)) { reason = "NTPFromDHCP is not empty, while FromDHCP is false"; return(false); } if ((ntpInformation.NTPManual != null) && !AreValidHosts(ntpInformation.NTPManual, ipAddressesMandatory, out reason)) { return(false); } } return(true); }
/// <summary> /// /// </summary> /// <returns></returns> /// <remarks> Is used in try-catch block. All exceptions will be handled in this block.</remarks> protected NTPInformation GetNTP() { NTPInformation ntp = null; RunStep(() => { ntp = Client.GetNTP(); }, "Get NTP Information"); DoRequestDelay(); return(ntp); }
public void GetNtpConfigurationTest() { RunTest(() => { NTPInformation ntpInformation = GetNTP(); Assert(ntpInformation != null, "NTP information not returned", "Check that DUT returned NTP information"); string reason = string.Empty; bool valid = ntpInformation.IsValidNTPInformation(false, out reason); Assert(valid, reason, "Validate NTP information"); }); }
public void SetInvalidIpv4NtpConfigurationTest() { RunTest <NetworkInterface>( new Backup <NetworkInterface>( () => { NetworkInterface ni = TurnOffDhcpIpv4(); return(ni); }), () => { NTPInformation testInformation = new NTPInformation(); testInformation.FromDHCP = false; testInformation.NTPManual = new NetworkHost[] { new NetworkHost() }; testInformation.NTPManual[0].Type = NetworkHostType.IPv4; testInformation.NTPManual[0].IPv4Address = "10.1.1"; RunStep(() => Client.SetNTP(testInformation.FromDHCP, testInformation.NTPManual), "Set NTP configuration - negative test", "Sender/InvalidArgVal/InvalidIPv4Address", true); DoRequestDelay(); NTPInformation currentInformation = GetNTP(); Assert(currentInformation != null, "The DUT did not return NTP configuration", "Check that NTP information returned from the DUT"); string reason; bool bValidConfiguration = currentInformation.IsValidNTPInformation(false, out reason); Assert(bValidConfiguration, reason, "Validate NTP configuration"); bool bFound = (currentInformation.NTPManual != null) && (currentInformation.NTPManual.Where(IP => IP.IPv4Address == "10.1.1"). FirstOrDefault() != null); Assert(!bFound, "The DUT returned invalid NTP Manual IP address", "Check if invalid address was not set"); }, (ni) => { if (ni.IPv4.Config.DHCP) { RestoreNetworkInterface(ni.token, ni); } }); }
void GetNTP() { DeviceClient client = null; try { client = new DeviceClient(new HttpBinding(new IChannelController[] { _listener }), new EndpointAddress(tbAddress.Text)); try { NTPInformation ntp = client.GetNTP(); } catch (FaultException exc) { BeginInvoke(new Action(() => { WriteLine("Fault!", System.Drawing.Color.BlueViolet); WriteLine(exc.Code.Name, System.Drawing.Color.Green); System.ServiceModel.FaultCode code = exc.Code.SubCode; string offset = " "; while (code != null) { WriteLine(string.Format("{0}Subcode: {1}", offset, code.Name), System.Drawing.Color.Green); offset = " " + offset; code = code.SubCode; } })); } BeginInvoke(new Action(() => WriteLine("OK"))); } catch (Exception exc) { if (client != null) { client.Abort(); } BeginInvoke(new Action(() => ReportError(exc))); //throw; } finally { StopAnimation(); } }
public TestTool.Onvif.NTPInformation GetNTP() { BeginMethod("GetNTP"); NTPInformation information = new NTPInformation(); NetworkCapabilities network = SimulatorConfiguration.ServicesConfiguration.DeviceServiceCapabilities.Network; if (network.NTPSpecified && network.NTP > 0) { } else { throw new NotImplementedException(); } EndMethod(); return(information); }
static void Main(string[] args) { Console.Out.WriteLine("Testing custom Http From Imported Files Generated By SvcUtil."); DeviceClient client = new DeviceClient(new CustomHttpBinding(true), new EndpointAddress("http://192.168.3.144:80/onvif/device_service")); //DeviceClient client = new DeviceClient(new CustomHttpBinding(true), new EndpointAddress("http://localhost:27468/Dut.asmx")); try { HostnameInformation info = client.GetHostname(); Console.WriteLine("HostnameInformation.Name: {0}", info.Name); Console.WriteLine("---------------------------------------------------"); try { NTPInformation ntp = client.GetNTP(); Console.WriteLine("NTPInformation.FromDHCP: {0}", ntp.FromDHCP); } catch (Exception exc) { Console.WriteLine(exc.Message); } Console.WriteLine("OK"); //client.BeginGetHostname(new AsyncCallback(GetHostnameCallback), client); } catch (Exception exc) { client.Abort(); Console.WriteLine(exc.Message); //throw; } Console.Out.WriteLine("Press <ENTER> to complete test."); Console.In.ReadLine(); }
public void SetSystemDateTimeNTPTest() { RunTest <NTPInformation>(new Backup <NTPInformation>( () => { NTPInformation backup = GetNTP(); return(backup); }), () => { NTPInformation ntp = new NTPInformation(); ntp.FromDHCP = false; ntp.NTPManual = new NetworkHost[] { new NetworkHost() }; ntp.NTPManual[0].Type = NetworkHostType.IPv4; ntp.NTPManual[0].IPv4Address = _environmentSettings.NtpIpv4; SetNTP(ntp); SystemDateTime testDateTimeSettins = new SystemDateTime(); testDateTimeSettins.DateTimeType = SetDateTimeType.NTP; testDateTimeSettins.DaylightSavings = true; testDateTimeSettins.TimeZone = new TestTool.Proxies.Device.TimeZone(); testDateTimeSettins.TimeZone.TZ = "PST8PDT,M3.2.0,M11.1.0"; SetSystemDateAndTime(testDateTimeSettins); SystemDateTime actualDateTime = GetSystemDateAndTime(); Assert(actualDateTime != null, "Date and time settings not found", "Check that DUT returned date and time settings"); Assert(actualDateTime.DateTimeType == testDateTimeSettins.DateTimeType, "DateTimeType has not been set", "Check that DateTimeType has been set. ", string.Format("Expected: {0}, actual: {1}", testDateTimeSettins.DateTimeType, actualDateTime.DateTimeType)); Assert(actualDateTime.DaylightSavings == testDateTimeSettins.DaylightSavings, "DaylightSavings not set", "Check that DaylightSavings has been set. ", string.Format("Expected: {0}, actual: {1}", testDateTimeSettins.DaylightSavings, actualDateTime.DaylightSavings)); Assert(actualDateTime.TimeZone != null, "The DUT did not return TimeZone settings", "Check that DUT returned TimeZone settings"); ValidateTimeZone(testDateTimeSettins.TimeZone.TZ, actualDateTime.TimeZone.TZ); if (actualDateTime.LocalDateTime != null) { string errorMessage; bool bDateTimeValid = actualDateTime.LocalDateTime.IsValidDateTime("LocalDateTime", out errorMessage); Assert(bDateTimeValid, errorMessage, "Validate LocalDateTime"); } else { WriteStep("Validate LocalDateTime", "LocalDateTime is NULL"); } if (actualDateTime.UTCDateTime != null) { string errorMessage; bool bDateTimeValid = actualDateTime.UTCDateTime.IsValidDateTime("UTCDateTime", out errorMessage); Assert(bDateTimeValid, errorMessage, "Validate UTCDateTime"); } else { WriteStep("Validate UTCDateTime", "UTCDateTime is NULL"); } }, (info) => { SetNTP(info, "Restore NTP information"); }); }
public void SetNtpConfigurationDnsFromDHCPTest() { NetworkInterface ni = null; RunTest <NTPInformation>( // Backup action new Backup <NTPInformation>(() => { NTPInformation originalInformation = GetNTP(); string reason = null; Assert((originalInformation != null) && originalInformation.IsValidNTPInformation(false, out reason), reason == null ? "Failed to get original NTP configuration" : reason, "Check that original NTP configuration returned from the DUT"); ni = TurnOnDhcpIpv4(); return(originalInformation); }), // Main action () => { NTPInformation testInformation = new NTPInformation(); testInformation.FromDHCP = true; SetNTP(testInformation); double timeout = ((double)_operationDelay) / 1000; BeginStep(string.Format("Wait {0} seconds to allow the DUT to interact with DHCP server", timeout.ToString("0.000"))); Sleep(_operationDelay); StepPassed(); NTPInformation actualInformation = GetNTP(); string reason = null; Assert((actualInformation != null) && actualInformation.IsValidNTPInformation(false, out reason), reason == null ? "Failed to get current NTP configuration" : reason, "Check that current NTP configuration returned from the DUT"); BeginStep("Check current NTP configuration"); bool bAllEquals; bool bEquals = (actualInformation.FromDHCP == testInformation.FromDHCP); LogStepEvent(string.Format("FromDHCP: expected - {0}, actual - {1}", testInformation.FromDHCP, actualInformation.FromDHCP)); bAllEquals = bEquals; string actualIpDescription; actualIpDescription = DeviceManagementNetworkTestSuite.DumpNetworkHostArray(actualInformation.NTPManual); string expectedAddress = "No Network Hosts"; if (actualInformation.NTPManual != null && actualInformation.NTPManual.Count() > 0) { bEquals = false; } else { bEquals = true; } LogStepEvent(string.Format("NTPManual: expected - {0}, actual - {1}", expectedAddress, actualIpDescription)); bAllEquals = bAllEquals && bEquals; /*************************************************/ actualIpDescription = DeviceManagementNetworkTestSuite.DumpNetworkHostArray(actualInformation.NTPFromDHCP); if (actualInformation.NTPFromDHCP == null) { bEquals = false; } else { bEquals = (actualInformation.NTPFromDHCP.Length > 0); } string expectedDescription = "List of NTP servers"; LogStepEvent(string.Format("NTPFromDHCP: expected - {0}, actual - {1}", expectedDescription, actualIpDescription)); bAllEquals = bAllEquals && bEquals; /*********************************************************/ if (!bAllEquals) { throw new AssertException("Current NTP configuration differs from configuration was set"); } StepPassed(); }, // Restore action (originalInformation) => { // if DHCP was ON, it has not been changed if (!ni.IPv4.Config.DHCP) { // restore network interface configuration RestoreNetworkInterface(ni.token, ni); } SetNTP(originalInformation, "Restore NTP configuration"); } ); }
public void SetNtpIpv6ConfigurationTest() { NetworkInterface ni = null; RunTest <NTPInformation>( new Backup <NTPInformation>(() => { NTPInformation originalInformation = GetNTP(); Assert(originalInformation != null, "The DUT did not return NTP configuration", "Check that DUT returned NTP information"); ni = TurnOffDhcpIpv6(); return(originalInformation); }), () => { NTPInformation testInformation = new NTPInformation(); testInformation.FromDHCP = false; testInformation.NTPManual = new NetworkHost[] { new NetworkHost() }; testInformation.NTPManual[0].Type = NetworkHostType.IPv6; testInformation.NTPManual[0].IPv6Address = _environmentSettings.NtpIpv6; SetNTP(testInformation); NTPInformation currentInformation = GetNTP(); Assert(currentInformation != null, "The DUT did not return NTP configuration", "Check that DUT returned NTP information"); BeginStep("Validate current NTP configuration"); bool bAllEquals; bool bEquals = (currentInformation.FromDHCP == testInformation.FromDHCP); LogStepEvent(string.Format("FromDHCP: expected - {0}, actual - {1}", testInformation.FromDHCP, currentInformation.FromDHCP)); bAllEquals = bEquals; string actualIpDescription; actualIpDescription = DeviceManagementNetworkTestSuite.DumpNetworkHostArray(currentInformation.NTPManual); NetworkHostType type = testInformation.NTPManual[0].Type; string expectedAddress = testInformation.NTPManual[0].IPv6Address; if ( currentInformation.NTPManual.Where( A => A.Type == type && A.IPv6Address == expectedAddress).Count() > 0) { bEquals = true; } else { bEquals = false; } string expectedDescription = string.Format("{0} should be presented", testInformation.NTPManual[0].IPv6Address); LogStepEvent(string.Format("NTPManual: expected - {0}, actual - {1}", expectedDescription, actualIpDescription)); bAllEquals = bAllEquals && bEquals; actualIpDescription = DeviceManagementNetworkTestSuite.DumpNetworkHostArray(currentInformation.NTPFromDHCP); if (currentInformation.NTPFromDHCP == null) { bEquals = true; } else { bEquals = (currentInformation.NTPFromDHCP.Length == 0); } expectedDescription = "No NTPFromDHCP"; LogStepEvent(string.Format("NTPFromDHCP: expected - {0}, actual - {1}", expectedDescription, actualIpDescription)); bAllEquals = bAllEquals && bEquals; if (!bAllEquals) { throw new AssertException( "Current NTP configuration differs from configuration set in previous step"); } StepPassed(); }, (originalInformation) => { SetNTP(originalInformation, "Restore NTP configuration"); if (ni.IPv6.Config.DHCP != IPv6DHCPConfiguration.Off) { RestoreNetworkInterface(ni.token, ni); } } ); }
protected void SetNTP(NTPInformation ntpInformation) { SetNTP(ntpInformation, "Set NTP configuration"); }
protected void SetNTP(NTPInformation ntpInformation, string stepName) { RunStep(() => { Client.SetNTP(ntpInformation.FromDHCP, ntpInformation.NTPManual); }, stepName); DoRequestDelay(); }
public void SetSystemDateTimeNTPTest() { NTPInformation initialNTPSettings = null; SystemDateTime initialDateTimeSettings = null; bool restoreSettings = false; RunTest(() => { initialDateTimeSettings = GetSystemDateAndTime(); initialNTPSettings = GetNTP(); var ntp = new NTPInformation { FromDHCP = false, NTPManual = new[] { new NetworkHost() } }; ntp.NTPManual[0].Type = NetworkHostType.IPv4; ntp.NTPManual[0].IPv4Address = _environmentSettings.NtpIpv4; SetNTP(ntp); restoreSettings = true; var testDateTimeSettins = new SystemDateTime { DateTimeType = SetDateTimeType.NTP, DaylightSavings = true, TimeZone = new TestTool.Proxies.Onvif.TimeZone { TZ = "PST8PDT,M3.2.0,M11.1.0" } }; SetSystemDateAndTime(testDateTimeSettins); SystemDateTime actualDateTime = GetSystemDateAndTime(); Assert(actualDateTime != null, "Date and time settings not found", "Check that DUT returned date and time settings"); Assert(actualDateTime.DateTimeType == testDateTimeSettins.DateTimeType, "DateTimeType has not been set", "Check that DateTimeType has been set. ", string.Format("Expected: {0}, actual: {1}", testDateTimeSettins.DateTimeType, actualDateTime.DateTimeType)); Assert(actualDateTime.DaylightSavings == testDateTimeSettins.DaylightSavings, "DaylightSavings not set", "Check that DaylightSavings has been set. ", string.Format("Expected: {0}, actual: {1}", testDateTimeSettins.DaylightSavings, actualDateTime.DaylightSavings)); Assert(actualDateTime.TimeZone != null, "The DUT did not return TimeZone settings", "Check that DUT returned TimeZone settings"); ValidateTimeZone(testDateTimeSettins.TimeZone.TZ, actualDateTime.TimeZone.TZ); if (actualDateTime.LocalDateTime != null) { string errorMessage; bool bDateTimeValid = actualDateTime.LocalDateTime.IsValidDateTime("LocalDateTime", out errorMessage); Assert(bDateTimeValid, errorMessage, "Validate LocalDateTime"); } else { WriteStep("Validate LocalDateTime", "LocalDateTime is NULL"); } if (actualDateTime.UTCDateTime != null) { string errorMessage; bool bDateTimeValid = actualDateTime.UTCDateTime.IsValidDateTime("UTCDateTime", out errorMessage); Assert(bDateTimeValid, errorMessage, "Validate UTCDateTime"); } else { WriteStep("Validate UTCDateTime", "UTCDateTime is NULL"); } }, () => { if (restoreSettings) { if (null != initialDateTimeSettings) { SynchronizeTime(initialDateTimeSettings); } if (null != initialNTPSettings) { SetNTP(initialNTPSettings); } } }); }
static int Main(string[] args) { string logFile = DateTime.Now.ToString("yyyy-MM-dd HH") + ".log"; bool alsoLog = args.Contains(LogSwitch); foreach (string s in HelpSwitches) { if (args.Contains(s)) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\r\n==================================================================================================="); Console.WriteLine("UpdateLocalTimeNTP.exe Usage: *NOTE: PROGRAM MUST BE RUN AS ADMIN TO APPLY CHANGES!*"); Console.WriteLine(" -nochange Test operation but make no clock changes."); Console.WriteLine(" -force (cannot be used with -nochange) Force an update even if drastically off or tiny."); Console.WriteLine(" -log Log operations to local folder for unattended troubleshooting."); Console.WriteLine(" Logs do not clean themselves up! Format=YEAR-MM-DD Hour.log (one log file per hour)."); Console.WriteLine(" Error logs are always written even if -log is not specified (ERROR-...log"); Console.WriteLine(" -nopause Exit upon completion (allow console window to close)."); Console.WriteLine(" -resetlist Re-add all servers, even ones that have failed in the past."); Console.WriteLine(" If servers.txt is missing, program will recreate it from internal list."); Console.WriteLine(" Edit active.txt or servers.txt if you want to use your own servers. (active.txt is rebuilt"); Console.WriteLine(" from servers.txt if present or internal list)."); Console.WriteLine(" -count:X (no spaces) Number of servers to use where X is between " + ServerListHandler.MIN_SERVER_REQUEST + " and " + ServerListHandler.MAX_SERVER_REQUEST + " (inclusive, default " + DefaultServerCount + ")"); Console.WriteLine(" -mincor:X (no spaces) Number of minimum MILLISECONDS to allow for adjustment (default, " + MinCorrection + " ms)"); Console.WriteLine(" -maxcor:X (no spaces) Number of maximum MINUTES to allow for adjustment (default, " + MaxCorrection + " minutes)"); Console.WriteLine(" Corrections above the max or below the min will be ignored without -force switch."); Console.WriteLine("=====================================================================================================\r\n"); return(0); } } if (args.Contains(FullServerListSwitch)) { ServerListHandler.ResetActiveServers(alsoLog, logFile); } if (args.Contains(ForceSwitch) && args.Contains(NoChangeSwitch)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*INVALID SWITCH COMBINATION! Force and No Change cannot be used", true, true, logFile); Common.WriteAndLogThisLine(" at the same time! Operation canceled*", true, true, logFile); return(-1); } if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*No Network Detected! Check your network connections and be sure ", true, true, logFile); Common.WriteAndLogThisLine(" this machine is connected to the Internet. Operation canceled*", true, true, logFile); return(-1); } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("Update Local Date/Time via NTP", alsoLog, false, logFile); Common.WriteAndLogThisLine("======================================================================", alsoLog, false, logFile); foreach (string a in args) { if (a.StartsWith(CountParameter) && a.Length > CountParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out serverCount)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-count:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + DefaultServerCount + " servers.", true, false, logFile); serverCount = DefaultServerCount; } else if (serverCount > ServerListHandler.MAX_SERVER_REQUEST || serverCount < ServerListHandler.MIN_SERVER_REQUEST) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-count:' flag value out of range " + "(" + ServerListHandler.MIN_SERVER_REQUEST + " to " + ServerListHandler.MAX_SERVER_REQUEST + " inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + DefaultServerCount + " servers.", true, false, logFile); serverCount = DefaultServerCount; } } } if (a.StartsWith(MaxCorParameter) && a.Length > MaxCorParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out MaxUserCorrection)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-maxcor:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MaxCorrection + " minutes.", true, false, logFile); MaxUserCorrection = MaxCorrection; } else if (MaxUserCorrection > 24 * 60 || MaxUserCorrection < 1) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-maxcor:' flag value out of range " + "(1 to " + (24 * 60).ToString() + " (=1 day) minutes inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MaxCorrection + " minutes.", true, false, logFile); MaxUserCorrection = MaxCorrection; } } } if (a.StartsWith(MinCorParameter) && a.Length > MinCorParameter.Length) { int index = a.IndexOf(':'); if (index > 0) { string c = a.Substring(a.IndexOf(':') + 1); if (!int.TryParse(c, out MinUserCorrection)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-mincor:' flag value not an integer", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MinCorrection + " milliseconds.", true, false, logFile); MinUserCorrection = MinCorrection; } else if (MinUserCorrection < 100 || MinUserCorrection > 600000) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): '-mincor:' flag value out of range " + "(100 to 600000 (=10 minutes) milliseconds inclusive)! ", true, false, logFile); Common.WriteAndLogThisLine(" Defaulting to " + MinCorrection + " milliseconds.", true, false, logFile); MinUserCorrection = MinCorrection; } } } } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = NormalColor; System.Diagnostics.Stopwatch programElapsedTime = new System.Diagnostics.Stopwatch(); programElapsedTime.Start(); Common.WriteAndLogThisLine(" Started: " + DateTimeOffset.Now.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Time corrections shown are additive differences between local and", alsoLog, false, logFile); Common.WriteAndLogThisLine(" remote (in seconds).", alsoLog, false, logFile); Common.WriteAndLogThisLine(" Negative numbers indicate local time is ahead of remote time.", alsoLog, false, logFile); if (args.Contains(NoChangeSwitch)) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" NO CHANGE switch active: No actual changes will be applied to the system.", alsoLog, false, logFile); Console.ForegroundColor = NormalColor; } //===========DO THE WORK Console.ForegroundColor = NormalColor; string[] servers = ServerListHandler.GetRandomActiveServers(serverCount, alsoLog, logFile); Common.WriteAndLogThisLine(" Using random " + serverCount + " servers from active.txt...", alsoLog, false, logFile); //try //{ // servers = System.IO.File.ReadAllLines("servers.txt"); //} //catch (Exception ex) if (servers == null || servers.Length < 3) { Console.ForegroundColor = ConsoleColor.Red; Common.WriteAndLogThisLine(" *Problem getting servers (null or too few), Operation Terminated!", alsoLog, true, logFile); Common.WriteAndLogThisLine(" Use '-resetlist' or delete 'active.txt' and 'servers.txt' to correct.", alsoLog, true, logFile); if (!args.Contains(NoPauseSwitch)) { Console.WriteLine("...press any key to terminate program..."); Console.ReadKey(true); } return(-1); } if (serverCount > servers.Length) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*Warning (non-fatal): Requested server count not available, use '-resetlist' and try again.", alsoLog, false, logFile); } Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("=Begin server communication============", alsoLog, false, logFile); foreach (string server in servers) { if (string.IsNullOrWhiteSpace(server)) { continue; } NTPInformation stuff = new NTPInformation(); NTP.InterrogateRemote(server, ref stuff); if (stuff.Success) { successes++; Console.ForegroundColor = SuccessColor; Common.WriteAndLogThisLine("-" + server + " success, offset=" + stuff.Correction.TotalSeconds.ToString(), alsoLog, false, logFile); corrections.Add(stuff.Correction.TotalSeconds); } else { failures.Add(server); Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine("*" + server + " fail! ", alsoLog, false, logFile);// + stuff.Error.Message); } //*/ } int returnVal = 0; Console.ForegroundColor = ImportantColor; Console.BackgroundColor = ConsoleColor.Black; Common.WriteAndLogThisLine("=End server communication==============", alsoLog, false, logFile); Console.ForegroundColor = NormalColor; Common.WriteAndLogThisLine(" Calculating...", alsoLog, false, logFile); if (corrections != null && corrections.Count >= 3) { Statistics.Boundaries b = Statistics.Outliers.GetOuterBoundaries(corrections, true); Common.WriteAndLogThisLine(" Upper Outlier Limit:" + b.High.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Lower Outlier Limit:" + b.Low.ToString(), alsoLog, false, logFile); double average = double.NaN; int datapoints = 0; foreach (double correction in corrections) { if (!double.IsNaN(correction)) { if (correction >= b.Low && correction <= b.High) { datapoints++; if (double.IsNaN(average)) { average = correction; } else { average += correction; } } else { Console.ForegroundColor = WarningColor; Console.BackgroundColor = ConsoleColor.Black; Common.WriteAndLogThisLine("*Outlier Ignored=" + correction.ToString(), alsoLog, false, logFile); } } } if (datapoints > 0 && !double.IsNaN(average)) { average = Math.Round(average / datapoints, 7); Console.ForegroundColor = NormalColor; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine(" Average difference : " + average.ToString() + " seconds."); if (Math.Abs(average) < ((float)MinUserCorrection / 1000) && !args.Contains(ForceSwitch)) { Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" Difference too small. Time drift considered OK.", alsoLog, false, logFile); } else if (Math.Abs(average) > (MaxCorrection * 60) && !args.Contains(ForceSwitch)) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Warning: Difference TOO BIG! Time drift needs manual intervention, or use", alsoLog, true, logFile); Common.WriteAndLogThisLine(" '-force' command-line switch.", alsoLog, true, logFile); returnVal = -1; } else if (!args.Contains(NoChangeSwitch)) { // maybe there should be a prompt here to ask the user if they didn't specify -nochange or -force??? if (!NTP.AdjustMachineTime(average)) { Console.ForegroundColor = ErrorColor; Common.WriteAndLogThisLine(" *FAILED TO UPDATE SYSTEM TIME!", alsoLog, true, logFile); Common.WriteAndLogThisLine(" *System API call failed!", alsoLog, true, logFile); returnVal = -1; } else { ServerListHandler.UpdateActiveServers(failures, alsoLog, logFile); // remove failed servers from active list } } else if (args.Contains(NoChangeSwitch)) { Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine(" NO CHANGE switch active: No actual changes will be applied to the system.", alsoLog, false, logFile); ServerListHandler.UpdateActiveServers(failures, alsoLog, logFile); } } else { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Some strangeness in the data (internal error). No changes made.", alsoLog, true, logFile); returnVal = -1; } } else if (corrections != null && corrections.Count < 3) { Console.ForegroundColor = WarningColor; Common.WriteAndLogThisLine(" *Not enough data to use! No changes made.", alsoLog, true, logFile); returnVal = -1; } else { Console.ForegroundColor = ErrorColor; Common.WriteAndLogThisLine(" *No data to use! No changes made.", alsoLog, true, logFile); returnVal = -1; } // all done, statistics then exit Console.ForegroundColor = NormalColor; Common.WriteAndLogThisLine(" Connections: " + successes + " Failures: " + failures.Count(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Finished at: " + DateTimeOffset.Now.ToString(), alsoLog, false, logFile); Common.WriteAndLogThisLine(" Process Duration (hh:mm:ss.fffffff): " + programElapsedTime.Elapsed.ToString(), alsoLog, false, logFile); Console.ForegroundColor = ImportantColor; Common.WriteAndLogThisLine("======================================================================", alsoLog, false, logFile); Console.BackgroundColor = StartingBackground; Console.ForegroundColor = StartingForeground; if (!args.Contains(NoPauseSwitch)) { Common.WriteAndLogThisLine("...press any key to terminate program...", false, false, null); if (Console.KeyAvailable) { do { Console.ReadKey(true); } while (Console.KeyAvailable); } Console.ReadKey(true); } return(returnVal); }